/*
 * BanBu_ChatViewController
 * @description 本文件提供对话界面的viewcontroller
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话界面的viewcontroller
 */

#import "BanBu_ChatViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "BanBu_MaskView.h"
#import "CJSONSerializer.h"
#import "BanBu_GraffitiController.h"
#import "BanBu_icePicController.h"
#import "BanBu_SearchIceViewController.h"
#import "BanBu_DialogueController.h"
#import "ShareViewController.h"
#import "WXOpen.h"
#import "BanBu_ThemeAndBubbleViewController.h"
#import "BanBu_ReportView.h"
#import "SCGIFImageView.h"
#import "BanBu_ImageView.h"
#import "BanBu_NavButton.h"
#import "UIBadgeView.h"
#import "BanBu_PhotoViewController.h"
#import "BanBu_TransmitViewController.h"
#import "PBJViewController.h"
#import "BanBu_PhotoAlbumViewController.h"
#import "LeveyTabBarController.h"
#import "BanBu_DigiViewController.h"
#import "UIViewController+Animation.h"
#import "BanBu_MagicKitViewController.h"
#import "BanBu_SnapController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "BanBu_MWNavigationController.h"
#import "CXAHyperlinkLabel.h"
#import "BanBu_FriendListController.h"
#import "BanBu_SendMsg.h"
#import "UIImage+JSMessagesView.h"
#import "JSMessageInputView.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_VIPAlert.h"
#import "BanBu_SmileLabelCell.h"
#import "BanBu_ImageViewCell.h"
#import "BanBu_VoiceViewCell.h"
#import "BanBu_LocationCell.h"
#import "BanBu_HintsViewCell.h"
#import "BanBu_VideoViewCell.h"
#import "BanBu_FullScreenCell.h"
#import "BanBu_SpecialTextCell.h"
#import "BanBu_EmoViewCell.h"
#import "BanBu_SmileLabel.h"
#import "BanBu_EmoStoreViewController.h"
#import "BanBu_EmoKeyboard.h"
#import "BanBu_CollectionController.h"
#import "BanBu_EmoManger.h"
#import "BanBu_ManuscriptViewController.h"
#import "BanBu_ManuscriptAPI.h"
#import "BanBu_MagicWordsViewController.h"
#import "BanBu_TitleView.h"

#define SmileStr  @"[装可爱]|[睁大眼睛]|[阴谋得逞]|[压力好大]|[兴高采烈]|[太帅了]|[睡觉]|[求饶]|[求包养]|[俏皮]|[怒发冲冠]|[目瞪口呆]|[路过]|[泪流满面]|[可怜兮兮]|[害羞]|[歌舞王后]|[高歌一曲]|[发奋图强]|[嘟嘟嘴]|[大跌眼镜]|[打怪兽]|[吃包子]|[不同意]"
// 832 行 发送图片

@interface BanBu_ChatViewController()
@end

@implementation BanBu_ChatViewController

@synthesize tableView = _tableView;

@synthesize rowt=_rowt;
@synthesize type=_type;
@synthesize latiArr=_latiArr;
BOOL iskeyboard = NO;
BOOL isSmileView = NO;
- (id)initWithPeopleProfile:(NSDictionary *)profile
{
    self = [super init];
    if (self)
    {
        self.profile = profile;
        
        MyAppDataManager.chatuid = [profile valueForKey:KeyFromUid];
        if ([[profile valueForKey:KeyFromUid] integerValue]<1000)
        {
            self.hidHeader = YES;
        }
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeArray: VALUE(@"facelist", profile)];
        
        NSMutableDictionary *taProfile=[[[NSMutableDictionary alloc]initWithDictionary:profile]autorelease];
        
        [taProfile setValue:jsonfrom forKey:@"facelist"];
        
        [UserDefaults setValue:taProfile forKey:@"zouni"];
    }
    return self;
}

#pragma mark - 跳转到地图
-(void)MakeBigMap
{
    CLLocationDegrees lat = [[_latiArr objectAtIndex:1]doubleValue]/1000000;
    CLLocationDegrees lon = [[_latiArr objectAtIndex:0] doubleValue]/1000000;
    
    BanBu_MakeBigMapViewController *BigMap=[[BanBu_MakeBigMapViewController alloc]initWithCGPoint:lat andLon:lon];
    
    [self.navigationController pushViewController:BigMap animated:YES];
    
    [BigMap release];
}

//调整界面
- (void)tableViewAutoOffset
{
    CGRect rect = _inputBar.frame;
    NSInteger cellNum = MyAppDataManager.dialogs.count;
    if(cellNum)
    {
        float offset = self.tableView.contentSize.height -rect.origin.y;
        offset +=5;
        
        NSLog(@"offset:%g",offset);
        
        if(offset<0)
            offset = 0;
        
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.5 animations:^{
            [self.tableView setContentInset:UIEdgeInsetsMake(-offset, 0, 0, 0)];
        }];
    }
}

#pragma mark - 系统方法
// 删除聊天记录之后要把ID 归零
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    NSLog(@"%@",NSHomeDirectory());
    self.titleView = [BanBu_TitleView instanceView];
    self.titleView.center = CGPointMake(160, 22);
    
    self.titleView.name = [MyAppDataManager IsInternationalLanguage:[MyAppDataManager theRevisedName:VALUE(KeyUname, _profile) andUID:VALUE(KeyUid, _profile)]];
    if ([_profile valueForKey:@"incityofname"])
    {
        self.titleView.position = [_profile valueForKey:@"incityofname"];
    }
    else
    {
        //获取定位地址
        [self getUserLocation];
    }
    
    NSLog(@"self.titleView:%@",self.titleView.name);
    [self.navigationController.navigationBar addSubview:self.titleView];
    
    self.isCloseInputBar = YES;
    self.isShowSound = YES; //默认显示输入框,录音按钮的切换显示
    self.isShowPlus = YES;  //默认显示输入框、键盘，“加号”按钮的切换显示
    self.isShowSmile = YES;  //默认显示输入框、键盘，“笑脸”按钮的切换显示
    self.view.multipleTouchEnabled = NO;
    _firstHere = YES;
    _latiArr=[[NSMutableArray alloc]init];
    MyAppDataManager.appChatController = self;
    sendMsgManager.appChatController = self;
    
    //返回按钮
    [self createBackButton];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendMsgAllType:) name:kSendMsgAllTypeNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendSnapText:) name:kSendSnapTextNotification object:nil];
    
    //设置静态背景，
    _bkView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-88)];
    
    _bkView.tag=606;
    
    //动态背景
    _bKGIFView = [[SCGIFImageView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-88)];
    _bKGIFView.tag = 607;
    
    [self.view addSubview:_bKGIFView];
    [self.view addSubview:_bkView];
    
    //初始化tableView
    [self initTableView];
    
    //初始化输入框部分
    [self initInputText];
    
    //当_showHeader为YES时，navgationBar显示有按钮
    if(!_hidHeader)
    {
        BanBu_NavButton *actionButton=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        actionButton.position = ButtonPositionRight;
        actionButton.frame=CGRectMake(0, 7, 40, 30);
        
        [actionButton addTarget:self action:@selector(changeList) forControlEvents:UIControlEventTouchUpInside];
        
        [actionButton setImage:[UIImage imageNamed:@"ic_topbar_more.png"] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:actionButton]autorelease];
        
        [actionButton release];
    }
    
    //这是是不是第一次进入的标志位
    if([MyAppDataManager.dialogs count]!=0)
    {
        if (self.titleView.name)
        {
            [UserDefaults setValue:@"1" forKey:self.titleView.name];
        }
    }
    
    //加载tableView时设置tableView显示最后一条消息
    CGFloat offset = self.tableView.contentSize.height-self.tableView.bounds.size.height;
    if(offset<1)
        offset = 0;
    [self.tableView setContentOffset:CGPointMake(0, offset)];
    
    //清除未读消息显示的气泡
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        //清除气泡
        [self clearOneUserFlag];
        
        //获取气泡
        [self getBubbleNames];
        
    });
    
    
    //20141020
    //zyfzyfzyf⬇️
    _shortUrl=[[NSMutableString alloc]init];
    //分享平台按钮
#warning 没有国际化
    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if ([langauage isEqualToString:@"zh-Hans"]) {
        //sina
        QuadCurveMenuItem *sinaMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_sina_icon.png"] withIntro:NSLocalizedString(@"sinaPlatform", nil)];
        // tencentWeibo
        QuadCurveMenuItem *tencentMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_tencent_icon.png"] withIntro:NSLocalizedString(@"tencentPlatform", nil)];
        
        // qzone
        QuadCurveMenuItem *qzoneMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_qzone_icon.png"] withIntro:NSLocalizedString(@"qqZonePlatform", nil)];
        //wechatLine
        QuadCurveMenuItem *weLineMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_timeline_icon.png"] withIntro:NSLocalizedString(@"wechatTimelinePlatform", nil)];
        // wechatSession
        QuadCurveMenuItem *weSessionMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_session_icon.png"] withIntro:NSLocalizedString(@"wechatSessionPlatform", nil)];
        // renren
        QuadCurveMenuItem *renrenMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_renren_icon.png"] withIntro:NSLocalizedString(@"renrenPlatForm", nil)];
        
        //facebook
        QuadCurveMenuItem *FacebookMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_facebook_icon.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem * TwitterItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_twitter_icon.png"] withIntro:@"Twitter"];
        
        NSArray *menus = [NSArray arrayWithObjects:sinaMenuItem, tencentMenuItem, qzoneMenuItem, weLineMenuItem, weSessionMenuItem, renrenMenuItem,FacebookMenuItem,TwitterItem, nil];
        [FacebookMenuItem release];
        [TwitterItem release];
        [sinaMenuItem release];
        [qzoneMenuItem release];
        [tencentMenuItem release];
        [weLineMenuItem release];
        [weSessionMenuItem release];
        [renrenMenuItem release];
        
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height+20) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    else
    {
        QuadCurveMenuItem *facebookMenuItem1 = [[QuadCurveMenuItem alloc] initWithCustomImage:nil withIntro:nil];
        facebookMenuItem1.userInteractionEnabled=NO;
        //facebook
        QuadCurveMenuItem *facebookMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"facebookForm.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem *twitterMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"twitterForm.png"] withIntro:@"Twitter"];
        NSArray *menus = [NSArray arrayWithObjects:facebookMenuItem1,facebookMenuItem,facebookMenuItem1,facebookMenuItem1,twitterMenuItem, nil];
        [facebookMenuItem release];
        [twitterMenuItem release];
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height +20) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    //zyfzyfzyf⬆️
    //20141020
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar addSubview:_titleView];
    
    MyAppDataManager.appChatController = self;
    sendMsgManager.appChatController = self;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    //隐藏标签栏
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
    
    self.isStayInChatPage = YES;
    
    [UIView setAnimationsEnabled:YES];
    [self performSelectorInBackground:@selector(setBGImage) withObject:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.tabBarController.tabBar.frame=CGRectMake(-320, 431, 320, 49);
    self.isColseKeyboard = YES;
    
    if(![UserDefaults valueForKey:@"firstInChat"])
    {
        if (_hidHeader)
        {//不显示详细个人资料时说明该人是系统推的消息，不显示阅后即焚提示页
            return;
        }
        
        UIImageView *notice = [[UIImageView alloc] initWithFrame:self.navigationController.view.bounds];
        notice.image = [UIImage imageNamed:@"guidance_chat.png"];
        notice.userInteractionEnabled = YES;
        
        NSString * hint = NSLocalizedString(@"snapHints1", nil);
        
        UILabel * hintLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        
        if (IS_IOS_7)
        {
            if (__MainScreen_Height<500)
            {
                hintLabel.frame = CGRectMake(90, __MainScreen_Height-28-58-15, 150, 60);
            }
            else
            {
                hintLabel.frame = CGRectMake(90, __MainScreen_Height-28-58-30, 150, 60);
            }
        }
        else
        {
            if (__MainScreen_Height<500)
            {
                hintLabel.frame = CGRectMake(60, __MainScreen_Height-28-58-20, 200, 40);
            }
            else
            {
                hintLabel.frame = CGRectMake(60, __MainScreen_Height-28-58-40, 200, 40);
            }
        }
        
        hintLabel.backgroundColor = [UIColor clearColor];
        hintLabel.numberOfLines = 3;
        hintLabel.textAlignment = UITextAlignmentCenter;
        hintLabel.textColor = [UIColor whiteColor];
        hintLabel.font = [UIFont systemFontOfSize:16];
        hintLabel.text = hint;
        hintLabel.adjustsFontSizeToFitWidth = YES;
        
        [notice addSubview:hintLabel];
        [hintLabel release];
        
        CATransition *animation = [CATransition animation];
        
        animation.duration = .0f;
        animation.timingFunction=UIViewAnimationCurveEaseInOut;
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionReveal;
        animation.subtype = kCATransitionFade;
        
        [self.view.window.layer addAnimation:animation forKey:@"animation"];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelImage:)];
        [notice addGestureRecognizer:tap];
        [tap release];
        
        [self.navigationController.view addSubview:notice];
        [notice release];
        
        [UserDefaults setValue:@"1" forKey:@"firstInChat"];
        
        if (self.titleView.name)
        {
            [UserDefaults setValue:@"1" forKey:self.titleView.name];
        }
    }
    
    if (_content)
    {
        [self easteregg:_content];
    }
}

-(void)cancelImage:(UITapGestureRecognizer *)sender
{
    [sender.view removeFromSuperview];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    self.tableView = nil;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_titleView removeFromSuperview];
    
    if (MyAppDataManager.playert)
    {
        MyAppDataManager.playert = nil;
    }
    
    [AppComManager cancalHandlesForObject:self];
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:1.0];
    
    [_inputView.textView resignFirstResponder];
    
    self.isStayInChatPage = NO;
    
    UIView * view = (UIView *)[self.navigationController.view viewWithTag:9876500];
    if ( view!=nil)
    {
        [view removeFromSuperview];
    }
    SCGIFImageView * view1 = (SCGIFImageView *)[self.navigationController.view viewWithTag:9876501];
    if ( view1!=nil)
    {
        [view1 removeFromSuperview];
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    _topBar.hidden = YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [_shortUrl release];
    _shortUrl = nil;
    [AppComManager cancalHandlesForObject:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSendMsgAllTypeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSendSnapTextNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    MyAppDataManager.appChatController = nil;
    sendMsgManager.appChatController = nil;
    [_inputBar removeObserver:self forKeyPath:@"frame"];
    [_tableView removeObserver:self forKeyPath:@"contentOffset"];
    [_topBar removeFromSuperview];
    _topBar = nil;
    [_tableView release],_tableView=nil;
    [_profile release],_profile=nil;
    [_latiArr release],_latiArr=nil;
    [_bkView release],_bkView = nil;
    [_bKGIFView release],_bKGIFView = nil;
    [_connection release],_connection = nil;
    [_returnBtTitle release],_returnBtTitle = nil;
    [_badgeView release],_badgeView = nil;
    _badgeValue = nil;
    
    [_snapImageView release],_snapImageView = nil;
    [_movieController release],_movieController = nil;
    
    [_timeLabel release],_timeLabel = nil;
    [_activityIndicator release],_activityIndicator = nil;
    
    [_headerView release],_headerView = nil;
    [super dealloc];
}

#pragma mark - 记录该人的输入框状态
-(BOOL)getInputState
{
    //文件路径
    NSString * filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"InputState"];
    
    NSDictionary * inputDic = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    if (inputDic == nil || MyAppDataManager.chatuid == nil || [inputDic valueForKey:MyAppDataManager.chatuid] == nil)
    {
        return NO;//默认普通模式
    }
    
    if ([[inputDic valueForKey:MyAppDataManager.chatuid] boolValue])
    {
        return YES;
    }
    else
    {
        return NO;//普通模式
    }
}

-(NSString *)getInputViewText
{
    //文件路径
    NSString * filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"InputState"];
    
    NSDictionary * inputDic = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    NSString * key = [NSString stringWithFormat:@"%@,%@",MyAppDataManager.chatuid,KeyContent];
    
    if (inputDic == nil || MyAppDataManager.chatuid == nil || ([[inputDic valueForKey:key] length]<=0))
    {
        return nil;
    }
    return [inputDic valueForKey:key];
}

-(void)recordInputState
{
    //文件路径
    NSString * filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"InputState"];
    
    NSMutableDictionary * inputDic = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    if (inputDic == nil)
    {
        inputDic = [NSMutableDictionary dictionaryWithCapacity:5];//设置空间大小
    }
    
    [inputDic setValue:[NSNumber numberWithBool:_inputView.snapText] forKey:MyAppDataManager.chatuid];
    [inputDic setValue:_inputView.textView.text forKey:[NSString stringWithFormat:@"%@,%@",MyAppDataManager.chatuid,KeyContent]];
    
    [NSKeyedArchiver archiveRootObject:inputDic toFile:filePath];
}

#pragma mark - 初始化tableView 和 tableView的tableHeaderView
//初始化tableView
-(void)initTableView
{
    //tableview 的headerView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-88) style:UITableViewStylePlain];
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    [tableView release];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    if(!_hidHeader)
    {
        //用户个人信息
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 64)];
        _headerView.backgroundColor = [UIColor clearColor];
        
        BanBu_HeaderView *header=[[BanBu_HeaderView alloc]initWithDelegate:self Selector:@selector(pushnext) Frame:CGRectMake(0, 0, 320, 64) TableView:self.tableView];
        header.backgroundColor = [UIColor clearColor];
        [header setStar:[MyAppDataManager IsInternationalLanguage:[self.profile valueForKey:@"sstar"]]];
        
        [header setHeadImaget:[self.profile valueForKey:@"uface"]];
        
        [header setVerify:![[self.profile valueForKey:@"verify"] isEqual:@"y"]];
        
        if([[self.profile allKeys] containsObject:@"gender"])
        {
            [header setAgeAndSext:[self.profile valueForKey:@"gender"] verify:[[self.profile valueForKey:@"verify"] boolValue]];
        }
        [header setNameLabelt:[MyAppDataManager theRevisedName:[self.profile valueForKey:@"pname"] andUID:[self.profile valueForKey:@"userid"]]];
        
        [header setAge:[self.profile valueForKey:@"oldyears"]];
        
        [_headerView addSubview:header];
        [header release];
        
        if (self.titleView.name)
        {
            if(![UserDefaults valueForKey:self.titleView.name])
            {
                BanBu_AlertView * alertView = [[BanBu_AlertView alloc]init];
                alertView.delegate = self;
                NSString * showText = NSLocalizedString(@"warningLabel", nil);
                [alertView initWithText:showText];
                alertView.frame = CGRectMake(0, 70, 320, alertView.textLabel.frame.size.height+6);
                [_headerView addSubview:alertView];
                [alertView release];
                _headerView.frame = CGRectMake(0, 0, 320, 64+alertView.frame.size.height);
                [UserDefaults setValue:@"1" forKey:self.titleView.name];
            }
        }
        [header setVIPFlag:[[self.profile valueForKey:@"userlevel"] integerValue]>0];
        self.tableView.tableHeaderView=_headerView;
    }
}

#pragma mark - 初始化对话输入框部分
//初始化输入框部分
-(void)initInputText
{
    //设置输入框部分
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    
    imageView.image = [[UIImage imageNamed:@"bottom-bar.png"] stretchableImageWithLeftCapWidth:2.0 topCapHeight:10.0];
    imageView.userInteractionEnabled = YES;
    
    //"+"号按钮
    UIButton *plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
    plusButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    plusButton.frame = CGRectMake(320-28-5, 8.0, 28.0, 28.0);
    _plusButton = plusButton;
    [plusButton addTarget:self action:@selector(plusAction:) forControlEvents:UIControlEventTouchUpInside];
    [plusButton setBackgroundImage:[ThemeManager getThemeImage:@"btn_plus_br.png"] forState:UIControlStateNormal];
    [plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    [imageView addSubview:plusButton];
    
    UIButton *smileButton = [UIButton buttonWithType:UIButtonTypeCustom];
    smileButton.frame = CGRectMake(320-28-5-5-28, 8.0, 28, 28);
    smileButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    _smileButton = smileButton;
    [smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
    [smileButton addTarget:self action:@selector(smileAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:smileButton];
    
    UIButton *actionsButton = [UIButton buttonWithType:UIButtonTypeCustom];
    actionsButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    _actionButton = actionsButton;
    actionsButton.frame = CGRectMake(3, 8, 58.0, 28);
    [actionsButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
    [actionsButton addTarget:self action:@selector(switchVoice:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:actionsButton];
    
    //输入框
    BOOL bl = [self getInputState];
    _inputView = [[JSMessageInputView alloc] initWithFrame:CGRectMake(_actionButton.frame.origin.x+60, 7,185, 30.0) snapMode:bl  delegate:self];
    _chatStringDefault = [self getInputViewText];
    
    _inputView.userInteractionEnabled = YES;
    _inputView.textView.backgroundColor = [UIColor clearColor];
    _inputView.backgroundColor = [UIColor clearColor];
    _inputView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _inputView.textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _inputView.textView.enablesReturnKeyAutomatically = YES;
    _inputView.textView.placeHolder = NSLocalizedString(@"normalPattern", nil);
    
    [imageView addSubview:_inputView];
    [_inputView release];
    
    _timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _timeButton.frame = CGRectMake(_actionButton.frame.origin.x+60, 8.0+4, 20, 20);
    _timeButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [_timeButton setImage:[UIImage imageNamed:@"label_Clock@2x.png"] forState:UIControlStateNormal];
    [_timeButton addTarget:self action:@selector(timeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    _timeLabel.font = [UIFont systemFontOfSize:10];
    _timeLabel.textAlignment = UITextAlignmentCenter;
    _timeLabel.backgroundColor = [UIColor clearColor];
    _timeButton.hidden = YES;
    _timeLabel.hidden = YES;
    if (sendMsgManager.textEffectiveTime<3)
    {
        sendMsgManager.textEffectiveTime = 3;
    }
    _timeLabel.text = [NSString stringWithFormat:@"%d",sendMsgManager.textEffectiveTime];
    [_timeButton addSubview:_timeLabel];
    
    [imageView addSubview:_timeButton];
    
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    
    imageView2.image = [[UIImage imageNamed:@"bottom-bar.png"] stretchableImageWithLeftCapWidth:2.0 topCapHeight:10.0];
    imageView2.userInteractionEnabled = YES;
    
    UIButton *plusButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    plusButton2.frame = CGRectMake(320-28-5, 8.0, 28.0, 28.0);
    _plusButton2 = plusButton2;
    [plusButton2 addTarget:self action:@selector(plusAction:) forControlEvents:UIControlEventTouchUpInside];
    [plusButton2 setBackgroundImage:[ThemeManager getThemeImage:@"btn_plus_br.png"] forState:UIControlStateNormal];
    [plusButton2 setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    [imageView2 addSubview:plusButton2];
    
    UIButton *smileButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    smileButton2.frame = CGRectMake(320-28-5-5-28, 8.0, 28, 28);
    _smileButton2 = smileButton2;
    [smileButton2 setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
    [smileButton2 addTarget:self action:@selector(smileAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageView2 addSubview:smileButton2];
    
    
    UIButton *actionsButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    _actionButton2 = actionsButton2;
    actionsButton2.frame = CGRectMake(3, 8, 58.0, 28);
    [actionsButton2 setImage:[ThemeManager getThemeImage:@"btn_voicekey.png"] forState:UIControlStateNormal];
    [actionsButton2 addTarget:self action:@selector(switchVoice:) forControlEvents:UIControlEventTouchUpInside];
    [imageView2 addSubview:actionsButton2];
    
    //录音按钮
    voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    voiceButton.tag = 1001;
    voiceButton.frame = CGRectMake(_actionButton2.frame.origin.x+58, 3,185, 38.0);
    [voiceButton setImage:[ThemeManager getThemeImage:@"btn_voice.png"]  forState:UIControlStateNormal];
    voiceButton.layer.cornerRadius = 5;
    voiceButton.layer.masksToBounds = YES;
    [voiceButton addTarget:self action:@selector(voiceTap) forControlEvents:UIControlEventTouchUpInside];
    [imageView2 addSubview:voiceButton];
    
    //录音时长按
    UILongPressGestureRecognizer *aLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(record:)];
    [voiceButton addGestureRecognizer:aLongPress];
    [aLongPress release];
    
    //翻滚的输入框，可见部分是输入框，隐藏部分是录音
    _inputBar = [[CFCube alloc] initWithFrame:CGRectMake(0, __MainScreen_Height-88,320,44)];
    _inputBar.delegate = self;
    _inputBar.visibleContentView = imageView;
    _inputBar.hiddenContentView = imageView2;
    [imageView release];
    [imageView2 release];
    [self.view addSubview:_inputBar];
    [_inputBar release];
    [_inputBar addObserver:self forKeyPath:@"frame" options:1 context:nil];
    [_tableView addObserver:self forKeyPath:@"contentOffset" options:1 context:nil];
    
    if(_chatStringDefault&&_chatStringDefault.length)
    {
        if(!self.previousTextViewContentHeight)
            self.previousTextViewContentHeight = 34;
        
        [_inputView.textView becomeFirstResponder];
        _inputView.textView.text = _chatStringDefault;
        [self textViewDidChange:_inputView.textView];
        _inputView.textView.text = _chatStringDefault;
        
        if (IS_IOS_7)
        {
            CGFloat maxHeight = [JSMessageInputView maxHeight];
            
            CGSize size = [_inputView.textView sizeThatFits:CGSizeMake(_inputView.textView.frame.size.width, maxHeight)];
            NSLog(@"_inputView.textView.contentSize:%@",NSStringFromCGSize(_inputView.textView.contentSize));
            [_inputView.textView scrollRectToVisible:CGRectMake(0, size.height+45, _inputView.textView.contentSize.width, 10) animated:YES];
        }
        else
        {
            [_inputView.textView scrollRectToVisible:CGRectMake(0, _inputView.textView.contentSize.height-15, _inputView.textView.contentSize.width, 10) animated:YES];
        }
        
        _inputView.textView.scrollEnabled = YES;
        self.isColseKeyboard = YES;
    }
    
    _chatStringDefault = nil;
}

//创建返回按钮
- (UIBarButtonItem*)createBackButton
{
    UIBarButtonItem *bar_itemreturn = nil;
    if (self.returnBtTitle)//对话、打招呼界面进入聊天
    {
        BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
        btn_return.position = ButtonPositionLeft;
        [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
        NSString *str = [NSString stringWithFormat:@" %@",NSLocalizedString(self.returnBtTitle, nil)];
        
        CGFloat btnLen = [str sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 30)].width;
        
        btn_return.frame=CGRectMake(0, 0, btnLen+20, 30);
        
        [btn_return setTitle:str forState:UIControlStateNormal];
        bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
        self.navigationItem.leftBarButtonItem = bar_itemreturn;
        [btn_return release];
        
        //设置气泡
        if ([self.returnBtTitle isEqualToString:@"sayHi"])
        {
            [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
        }
        else
        {
            [self setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
        }
    }
    else//个人资料界面进入聊天
    {
        BanBu_NavButton *btn_return = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
        btn_return.position = ButtonPositionLeft;
        [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
        
        bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
        self.navigationItem.leftBarButtonItem = bar_itemreturn;
        [btn_return release];
    }
    
    return bar_itemreturn;
}

//获取气泡的文件夹名字和id
-(void)getBubbleNames
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    NSString * bubbleDirPath;
    NSDictionary * bubbleNameDic = [NSDictionary dictionaryWithContentsOfFile:[fileName stringByAppendingPathComponent:@"bubbleInfo.plist"]];
    
    if (bubbleNameDic.count <= MyAppDataManager.bubbleNameDic.count)
    {
        return;
    }
    
    for (int i =0 ; i < bubbleNameDic.count; i++)
    {
        NSString * bubbleName =[NSString stringWithFormat:@"bubble_%d",i];
        bubbleDirPath = [fileName stringByAppendingPathComponent:bubbleName];
        bubbleDirPath = [bubbleDirPath stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
        
        UIImage * image = [UIImage imageWithContentsOfFile:bubbleDirPath];
        if (!image)
        {
            continue;
        }
        [MyAppDataManager.bubbleNameDic setValue:bubbleName forKey:[NSString stringWithFormat:@"%d",i]];
    }
}

#pragma mark - 显示设置的背景图片
//设置背景
-(void)setBGImage
{
    //获取背景图片的名字，如果没有设置过，则显示默认图片MyAppDataManager.selectedBgIndex=0
    if (MyAppDataManager.selectedBgIndex < 2000)//选择的是推荐图片
    {
        if (MyAppDataManager.selectedBgIndex < 0)//选择的是动态图
        {
            self.bKGIFView.hidden = NO;
            self.bKGIFView.gifFile = nil;
            NSString * GIFfile = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_GIF"] stringByAppendingPathComponent:[NSString stringWithFormat:@"chat_bg_%d.gif",-MyAppDataManager.selectedBgIndex - 1]];
            if ([[NSFileManager defaultManager]fileExistsAtPath:GIFfile])
            {
                self.bKGIFView.gifFile = GIFfile;
                self.bkView.hidden = YES;
                [self.view insertSubview:self.bKGIFView atIndex:0];
            }
            else
            {
                [self performSelectorOnMainThread:@selector(setLoading:) withObject:[NSNumber numberWithInt:1] waitUntilDone:YES];
            }
        }
        else//选择的是静态图
        {
            self.bkView.hidden = NO;
            NSString * imagefile = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_photo"];
            
            NSString * imageIndex = [NSString stringWithFormat:@"chat_bg_%02d.jpg",MyAppDataManager.selectedBgIndex - 1];
            if (MyAppDataManager.selectedBgIndex == 0)
            {
                imageIndex = [NSString stringWithFormat:@"chat_bg_%02d.jpg",MyAppDataManager.selectedBgIndex];
                UIImage * image = [UIImage imageNamed:imageIndex];
                self.bkView.image = image;
                self.bkView.frame = CGRectMake(0, 0, 320, __MainScreen_Height-88);
                self.bKGIFView.hidden = YES;
                return;
            }
            
            if ([[NSFileManager defaultManager]fileExistsAtPath:[imagefile stringByAppendingPathComponent:imageIndex]])
            {
                UIImage * image = [UIImage imageWithContentsOfFile:[imagefile stringByAppendingPathComponent:imageIndex]];
                self.bkView.image = image;
                self.bkView.frame = CGRectMake(0, 0, 320, __MainScreen_Height-88);
                self.bKGIFView.hidden = YES;
            }
            else
            {
                [self performSelectorOnMainThread:@selector(setLoading:) withObject:[NSNumber numberWithInt:1] waitUntilDone:YES];
            }
        }
    }
    else//选择的是相册中的图片；索引大于2000
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString * chatBackPath = [[paths objectAtIndex:0] stringByAppendingString:@"/chatbackImage.png"];
        self.bkView.image = [UIImage imageWithContentsOfFile:chatBackPath];
        
        self.bkView.frame = CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height);
        self.bkView.hidden = NO;
        self.bKGIFView.hidden = YES;
    }
}

#pragma mark - 获取用户定位地址
//获取用户定位地址
-(void)getUserLocation
{
    NSDictionary * userInfoDic = [MyAppDataManager getPersonInfoByOne:MyAppDataManager.chatuid];
    NSString * plat = [userInfoDic valueForKey:@"poslat"];
    NSString * plong = [userInfoDic valueForKey:@"poslong"];
    
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:[plat floatValue]/1000000 longitude:[plong floatValue]/1000000];
    
    [AppComManager getBanBuPosition:loc delegate:self];
}

//设置地理位置
- (void)updateTitleWithString:(NSString *)_info
{
    _titleView.name = [MyAppDataManager IsInternationalLanguage:[MyAppDataManager theRevisedName:VALUE(KeyUname, _profile) andUID:VALUE(KeyUid, _profile)]];
    self.titleView.position = _info;
}

-(void)setLoading:(NSNumber *)index
{
    if ([index intValue] == 1)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"bgDownloading", nil) activityAnimated:NO duration:2.0];
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"bgDownloaded", nil) activityAnimated:NO duration:2.0];
    }
}

//清除气泡
-(void)clearOneUserFlag
{
    //更改数据库，将这个人的未读条数清零
    [MyAppDataManager setUnreadNumber:0 With:MyAppDataManager.chatuid];
}

//弹出语音录制时间过短提示
-(void)voiceTap
{
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"timeshortNoticte", nil) activityAnimated:NO duration:1.0];
}

//要添加一个按钮“设置聊天背景”
-(void)changeList
{
//    if (IS_IOS_8)
//    {
//        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        __block BanBu_ChatViewController * bself = self;
//        UIAlertAction *seeMoreAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"seeMoreMessage", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            BOOL isMore = [MyAppDataManager readMoreTwentyMessage];
//            if(isMore)
//            {
//                [bself.tableView reloadData];
//                [bself.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
//            }
//        }];
//        
//        // Add the actions.
//        [alert addAction:seeMoreAction];
//        
//        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"deleteMes", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            [MyAppDataManager deleteAllChattingRecordsOfOnePerson:MyAppDataManager.chatuid];
//            
//            NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs lastObject]];
//            [peoDic setValue:@"" forKey:KeyContent];
//            [peoDic setValue:[NSNumber numberWithInteger:ChatStatusNone] forKey:KeyStatus];
//            [peoDic setValue:MyAppDataManager.chatuid forKey:KeyFromUid];
//            [peoDic setValue:[NSNumber numberWithInt:0] forKey:KeyType];
//            [peoDic setValue:[NSNumber numberWithInt:0] forKey:KeyUnreadNum];
//            
//            [MyAppDataManager setTalkPeopleOne:peoDic];
//            
//            [MyAppDataManager.dialogs removeAllObjects];
//            [MyAppDataManager.cellRowMapDic removeAllObjects];
//            [bself.tableView reloadData];
//        }];
//        
//        // Add the actions.
//        [alert addAction:deleteAction];
//        
//        
//        UIAlertAction *setBGAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"setBGAndBubble", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            BanBu_ThemeAndBubbleViewController * theViewController = [[BanBu_ThemeAndBubbleViewController alloc]init];
//            [bself.navigationController pushViewController:theViewController animated:YES];
//            [theViewController release];
//            theViewController = nil;
//        }];
//        
//        // Add the actions.
//        [alert addAction:setBGAction];
//        
//        __block BOOL bisBlack = _isBlack;
//        UIAlertAction *BlackAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"pullBlackTitle", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            NSString *baction = @"black";
//            NSMutableDictionary *pars = [NSMutableDictionary dictionary];
//            [pars setValue:[_profile valueForKey:@"userid"] forKey:LinkTouID];
//            [pars setValue:baction forKey:Action];
//            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", ni) activityAnimated:YES];
//            [AppComManager getBanBuData:BanBu_Set_Friend_Link par:pars delegate:self];
//            bself.navigationController.view.userInteractionEnabled = NO;
//            
//            bisBlack = YES;
//        }];
//        
//        // Add the actions.
//        [alert addAction:BlackAction];
//        
//        __block JSMessageInputView * binputView = _inputView;
//        UIAlertAction *BlackAndReportAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"pullBlackAndReport", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            [binputView.textView resignFirstResponder];
//            BanBu_ReportView * aReportView = [[BanBu_ReportView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height+20) andType:REPORT_USER];
//            aReportView.delegate = bself;
//            [bself.navigationController.view addSubview:aReportView];
//            [aReportView release];
//            aReportView = nil;
//        }];
//        [alert addAction:BlackAndReportAction];
//        [MyAppDelegate.window.rootViewController presentViewController:alert animated:YES completion:nil];
////        [alert release];
//        alert = nil;
//        return;
//    }
    UIActionSheet *aSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"seeMoreMessage",nil),NSLocalizedString(@"deleteMes", nil),NSLocalizedString(@"setBGAndBubble", nil),NSLocalizedString(@"pullBlackTitle",nil),NSLocalizedString(@"pullBlackAndReport", nil), nil];
    aSheet.tag = 10101;
    [aSheet showInView:self.view.window];
    [aSheet release];
    aSheet = nil;
}

#pragma mark - 查看用户的个人资料
//查看自己的个人资料
-(void)pushself
{
    NSLog(@"%@",[UserDefaults valueForKey:MyAppDataManager.useruid]);
    BanBu_PersonDataViewController *myProfile1 = [[BanBu_PersonDataViewController alloc] initWithProfile:[UserDefaults valueForKey:MyAppDataManager.useruid]];
    [self.navigationController pushViewController:myProfile1 animated:YES];
    [myProfile1 release];
}

#pragma 进入个人资料详情
//查看别人的个人资料
-(void)pushnext
{
    if ([MyAppDataManager.chatuid integerValue]<1000)
    {
        return;
    }
    
    BanBu_PersonDataViewController *profile = nil;
    for(UIViewController *vc in [self.navigationController viewControllers])
        if([vc isKindOfClass:[BanBu_PersonDataViewController class]])
        {
            profile = (BanBu_PersonDataViewController *)vc;
            break;
        }
    if(profile)
    {
        [self.navigationController popToViewController:profile animated:YES];
    }
    else
    {
        NSDictionary * usserInfoDic = [MyAppDataManager getPersonInfoByOne:MyAppDataManager.chatuid];
        
        //        NSMutableDictionary  *proDic = [[NSMutableDictionary alloc] initWithDictionary:usserInfoDic];
        //
        //        [proDic setValue:[MyAppDataManager getTheLastOnlineTime:[proDic valueForKey:@"ltime"]] forKey:@"ltime"];
        //        [proDic setValue:[NSArray array] forKey:KeyFacelist];
        
        profile = [[BanBu_PersonDataViewController alloc] initWithProfile:usserInfoDic];
        
        [self.navigationController pushViewController:profile animated:YES];
        [profile release];
        //        [proDic release];
    }
}

//返回上一界面（对话列表界面或个人资料界面）
-(void)popself
{
    BanBu_SnowView * snow = (BanBu_SnowView *)[self.view viewWithTag:40004];
    if (snow)
    {
        snow.delegate = nil;
        snow = nil;
    }
    //记录悄悄话模式还是普通模式
    [self recordInputState];
    MyAppDataManager.chatuid = nil;
    MyAppDataManager.appChatController = nil;
    sendMsgManager.appChatController = nil;
    if(_chatStringDefault.length)//从相册跳转过来的带有这个参数，为默认对话文字
    {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if (MyAppDataManager.secondaryTalkPeople.count<=0 && self.returnBtTitle.length>0)
    {
        [self.navigationController popToRootViewControllerAnimated:YES];//返回对话界面
    }
    else
    {
        //返回上一界面（可能是对话界面、可能是打招呼界面，具体是哪一界面要看上次是压入的那个界面）
        [self.navigationController popViewControllerAnimated:YES];
    }
    self.keyboardview.view.hidden = YES;
}


#pragma mark - 设置返回按钮显示消息未读数量
//设置返回按钮的气泡
- (void)setBadgeValue:(NSString *)badgeValue withButtonIndex:(NSInteger)_index
{
    [_badgeValue release];
    _badgeValue = [badgeValue retain];
    if(!badgeValue||![badgeValue intValue] || self.returnBtTitle.length <=0)
    {
        if(self.badgeView)
        {
            self.badgeView.hidden = YES;
        }
    }
    else
    {
        float width = [badgeValue sizeWithFont:[UIFont boldSystemFontOfSize:14]].width+12;
        if(!self.badgeView)
        {
            self.badgeView = [[[UIBadgeView alloc] initWithFrame:CGRectMake(self.navigationItem.leftBarButtonItem.customView.bounds.size.width-width/3, -2, width, 20)] autorelease];
            
            self.badgeView.backgroundColor = [UIColor clearColor];
            self.badgeView.badgeColor = [UIColor redColor];
            self.badgeView.tag = _index;
            [self.navigationItem.leftBarButtonItem.customView addSubview:_badgeView];
        }
        
        self.badgeView.badgeString = badgeValue;
        self.badgeView.hidden = NO;
        
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.5
                         animations:^{
                             self.badgeView.frame = CGRectMake(self.navigationItem.leftBarButtonItem.customView.bounds.size.width - width/3, -2, width, 20);
                         }];
    }
}

//kvo，检测tableview的高度变化和输入框的变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    CGRect rect = [[change objectForKey:@"new"] CGRectValue];
    
    if([keyPath isEqualToString:@"contentOffset"])
    {
        if (self.tableView.contentOffset.y<-30)
        {
            if (self.activityIndicator == nil)
            {
                _refreshTable = YES;
                self.activityIndicator = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
                self.activityIndicator.hidden = NO;
                [self.activityIndicator startAnimating];
                CGFloat y = (__MainScreen_Height)/2;
                self.activityIndicator.frame = CGRectMake(145,  y, 30, 30);
                [self.view addSubview:self.activityIndicator];
            }
        }
        return;
    }
    
    [self tableViewAutoOffset];
    
    if(rect.origin.y == __MainScreen_Height-88)
    {
        [_actionButton setImage:_actionButton.selected?[ThemeManager getThemeImage:@"btn_voicekey.png"]:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
        CGRect frame = _inputView.frame;
        
        if(_inputView.frame.size.height == frame.size.height)
            return;
        _inputView.frame = frame;
        frame = _inputBar.visibleContentView.frame;
        frame.origin.y = 0;
        
        _inputBar.visibleContentView.frame = frame;
        
        CGRect rect = _plusButton.frame;
        rect.origin.y = 8.0;
        _plusButton.frame = rect;
        rect = _smileButton.frame;
        rect.origin.y = 8.0;
        _smileButton.frame = rect;
        rect = _actionButton.frame;
        rect.origin.y = 8.0;
        _actionButton.frame = rect;
    }
    
    if(rect.origin.y < __MainScreen_Height-88)
    {
        BanBu_MaskView *maskView = (BanBu_MaskView *)[self.view viewWithTag:MaskViewTag];
        if(maskView == nil)
        {
            maskView = [[BanBu_MaskView alloc] initWithFrame:self.view.bounds];
            maskView.backgroundColor = [UIColor clearColor];
            maskView.tag = MaskViewTag;
            maskView.delegate = self;
            [maskView setDidTouchedSelector:@selector(tapped:)];
            maskView.userInteractionEnabled = YES;
            [self.view addSubview:maskView];
            
            [self.view bringSubviewToFront:_smileView];
            [self.view bringSubviewToFront:_inputBar];
            
            //            if (self.isShowPlus)
            //            {
            //                [self.view bringSubviewToFront:_smileView];
            //                [self.view bringSubviewToFront:_inputBar];
            //            }
            //            else
            //            {
            //                [self.view bringSubviewToFront:_inputBar];
            //                [self.view bringSubviewToFront:_smileView];
            //            }
            
            
            [maskView addSubview:_timePicker];
            [maskView release];
        }
        else
            maskView.hidden = NO;
    }
}
#pragma mark - 普通模式<==>阅后即焚模式

-(JSInputFieldStyle)inputFieldStyle
{
    if (_inputView.snapText)
    {
        return JSInputFieldStyleBlack;
    }
    return JSInputFieldStyleGrey;
}

//设置是否发送阅后即焚文本
-(void)sendSnapText:(NSNotification *)notifi
{
    _inputView.inputFieldBack.image = [UIImage inputField];
    
    if ([[[notifi object]valueForKey:@"isSnapText"] boolValue])
    {
        _timeButton.hidden = NO;
        _timeLabel.hidden = NO;
        
        _inputView.textView.textColor = [UIColor whiteColor];
        //切换输入框背景
        _inputView.inputFieldBack.image = [UIImage inputField];
        
        UIImageView * imageView1 = (UIImageView *)_inputBar.visibleContentView;
        imageView1.image = [[UIImage imageNamed:@"bottom-bar_black.png"] stretchableImageWithLeftCapWidth:2.0 topCapHeight:10.0];
    }
    else//表情按钮复原
    {
        _inputView.textView.textColor = [UIColor blackColor];
        
        UIImageView * imageView1 = (UIImageView *)_inputBar.visibleContentView;
        imageView1.image = [[UIImage imageNamed:@"bottom-bar.png"] stretchableImageWithLeftCapWidth:2.0 topCapHeight:10.0];
        
        if(_timePicker.hidden == NO)
        {
            if (_smileView)
            {
                [UIView setAnimationsEnabled:YES];
                [UIView animateWithDuration:0.4
                                 animations:^{
                                     _smileView.frame =CGRectMake(0, __MainScreen_Height-260, 320, SmileViewDefaultHeight);
                                     _inputBar.frame = CGRectMake(0, _smileView.frame.origin.y-_inputBar.frame.size.height, 320, _inputBar.frame.size.height);
                                 }
                 ];
            }
            else
            {
                self.isCloseInputBar = YES;
                [_inputView.textView becomeFirstResponder];
            }
        }
        _timeButton.hidden = YES;
        _timePicker.hidden = YES;
        _timeLabel.hidden = NO;
    }
}

#pragma mark - 语音、表情、破冰语、键盘切换
-(void)resetKeyboard
{
    [_keyboardview.view removeFromSuperview];
    _keyboardview = [MyAppDataManager.emoKeyboard retain];
    _keyboardview.view.hidden = NO;
    [_smileView addSubview:_keyboardview.view];
}

#pragma mark - 点击对话框中的“+”号按钮
//破冰语
- (void)plusAction:(UIButton *)button
{
    self.isShowPlus = !self.isShowPlus;
    [button setImage:self.isShowPlus?[UIImage imageNamed:@"btn_plus.png"]:[ThemeManager getThemeImage:@"btn_keyboard.png"] forState:UIControlStateNormal];//不选中模式，显示表情图标（点击后，内容将显示表情）,显示键盘；选中模式时，显示键盘图标（点击后，内容将显示键盘），显示各个表情
    
    if (!self.isShowSmile)//如果显示的图标是键盘时，将键盘换为笑脸
    {
        self.isShowSmile = YES;
        [_smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
    }
    if (!self.isShowSound)
    {
        self.isShowSound = YES;
        [_actionButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
        [self switchBetweenHiddenAndvisible];
    }
    if (!_timePicker.hidden)
    {
        _timePicker.hidden = YES;
    }
    _keyboardview.view.hidden = YES;
    
    if (!self.isShowPlus)
    {
        if(!_smileView)
        {
            //2014年11月04日15:15:00 by yinlinlin 修改判断,主要是为了解决“+”号按钮偶尔点击不管用的问题
            if (self.smileViewBackup)
            {
                _smileView = [self.smileViewBackup retain];
            }
            else
            {
                if (MyAppDataManager.smileViewBackup)
                {
                    _smileView = [MyAppDataManager.smileViewBackup retain];
                }
                else
                {
                    [MyAppDataManager setSmileView];
                    _smileView = [MyAppDataManager.smileViewBackup retain];
                }
            }
            
            //修改完成
            _smileView.chatViewController = self;
            _smileView.type = SmileViewAddType;
            _smileView.delegate = self;
            [self.view addSubview:_smileView];
            
            [_smileView release];
            [_smileView.pageControl setFrame:CGRectMake(0, 190, 320, 10)];
            
            [_actionButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
            isSmileView = NO;
            
            self.isCloseInputBar = NO;
            [_inputView.textView resignFirstResponder];
            
            [self.view bringSubviewToFront:_inputBar];
        }
        else
        {
            if (_smileView.type == SmileViewSmileType || _smileView.type == SmileViewCharactersPaintedType)//破冰语模式时
            {
                if (!self.isShowPlus)       //如果现在图标显示的是键盘，则加载笑脸
                {
                    _smileView.type = SmileViewAddType;
                    self.isCloseInputBar = NO;
                    [_inputView.textView resignFirstResponder];
                }
                else                        //否则显示键盘
                {
                    self.isCloseInputBar = YES;
                    [_inputView.textView becomeFirstResponder];
                }
            }
            else if(self.isShowPlus)
            {
                self.isCloseInputBar = YES;
                [_inputView.textView becomeFirstResponder];
            }
            else                    //不是破冰语模式时，显示键盘
            {
                self.isCloseInputBar = NO;
                [_inputView.textView resignFirstResponder];
            }
        }
    }
    else
    {
        self.isCloseInputBar = YES;
        [_inputView.textView becomeFirstResponder];
    }
    if ([_inputView.textView isFirstResponder])
    {
        return;
    }
    [UIView setAnimationsEnabled:YES];
    [UIView animateWithDuration:.4
                     animations:^{
                         _smileView.frame = CGRectMake(0, __MainScreen_Height-260, 320, SmileViewDefaultHeight);
                         _inputBar.frame = CGRectMake(0, _smileView.frame.origin.y-_inputBar.frame.size.height, 320, _inputBar.frame.size.height);
                     }
     ];
    _keyboardview.view.hidden = YES;
}



#pragma mark - 点击对话框的笑脸按钮
- (void)smileAction:(UIButton *)button
{
    [_actionButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
    isSmileView = NO;
    
    self.isShowSmile = !self.isShowSmile;
    
    [button setImage:self.isShowSmile?[ThemeManager getThemeImage:@"btn_smlie.png"]:[UIImage imageNamed:@"btn_keyboard.png"] forState:UIControlStateNormal];//不选中模式，显示表情图标（点击后，内容将显示表情）,显示键盘；选中模式时，显示键盘图标（点击后，内容将显示键盘），显示各个表情
    
    //如果“+”按钮按钮显示的是“键盘”，就将“键盘”换为“+”号
    if (!self.isShowPlus)
    {
        self.isShowPlus = YES;
        [_plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    }
    if (!self.isShowSound)
    {
        self.isShowSound = YES;
        [_actionButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
        [self switchBetweenHiddenAndvisible];
    }
    
    if (!_timePicker.hidden)
    {
        _timePicker.hidden = YES;
    }
    
    
    
    if (!self.isShowSmile)
    {
        if (!_smileView)//不存在笑脸或破冰语视图
        {
            _smileView = nil;
            _smileView = [self.smileViewBackup retain];
            _smileView.chatViewController = self;
            [_smileView.pageControl setFrame:CGRectMake(0, 164, 320, 10)];
            _smileView.type = SmileViewSmileType;
            _smileView.delegate = self;
            
            self.keyboardview = [MyAppDataManager.emoKeyboard retain];
            
            _keyboardview.delegate = self;
            _keyboardview.view.hidden = NO;
            [_smileView addSubview:_keyboardview.view];
            
            [self.view addSubview:_smileView];
            
            [self.view bringSubviewToFront:_inputBar];
            [_smileView release];
            self.isCloseInputBar = NO;
            [_inputView.textView resignFirstResponder];//关闭键盘vc
        }
        else//存在视图时
        {
            _keyboardview.view.hidden = NO;
            if (!_keyboardview)
            {
                self.keyboardview = [[BanBu_EmoKeyboard alloc]init];
                _keyboardview.delegate = self;
                _keyboardview.view.frame = CGRectMake(0, 0, 320, 216);
                
                [_smileView addSubview:_keyboardview.view];
            }
            
            if (_smileView.type == SmileViewAddType)//破冰语模式时
            {
                if (!self.isShowSmile)       //如果现在图标显示的是键盘，则加载笑脸
                {
                    _smileView.type = SmileViewSmileType;
                    self.isCloseInputBar = NO;
                    [_inputView.textView resignFirstResponder];
                }
                else                        //否则显示键盘
                {
                    self.isCloseInputBar = YES;
                    [_inputView.textView becomeFirstResponder];
                }
            }
            else if(self.isShowSmile)
            {
                self.isCloseInputBar = YES;
                [_inputView.textView becomeFirstResponder];
            }
            else                    //不是破冰语模式时，显示键盘
            {
                self.isCloseInputBar = NO;
                [_inputView.textView resignFirstResponder];
            }
        }
    }
    else
    {
        //        _keyboardview.view.hidden = YES;
        self.isCloseInputBar = YES;
        [_inputView.textView becomeFirstResponder];
    }
    
    if ([_inputView.textView isFirstResponder])
    {
        return;
    }
    
    [UIView setAnimationsEnabled:YES];
    [UIView animateWithDuration:0.4
                     animations:^{
                         _smileView.frame = CGRectMake(0, __MainScreen_Height-260, 320, SmileViewDefaultHeight);
                         _inputBar.frame = CGRectMake(0, _smileView.frame.origin.y-_inputBar.frame.size.height, 320, _inputBar.frame.size.height);
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

//隐私模式时表情按钮切换为定时按钮，这是定时按钮的响应方法
-(void)timeAction:(UIButton *)button
{
    self.isColseKeyboard =YES;
    self.isCloseInputBar = NO;
    [_inputView.textView resignFirstResponder];
    
    self.isCloseInputBar = YES;
    if (_timePicker == nil)
    {
        self.timeArray = [NSArray arrayWithObjects:@"3s",@"4s",@"5s",@"6s",@"7s",@"8s",@"9s",@"10s", nil];
        UIPickerView * timePicker = [[UIPickerView alloc]init];
        _timePicker = timePicker;
        _timePicker.backgroundColor = [UIColor lightGrayColor];
        _timePicker.delegate = self;
        _timePicker.dataSource = self;
        _timePicker.frame = CGRectMake(0, __MainScreen_Height-216, 320, 216);
        [self.view addSubview:_timePicker];
        
        if (sendMsgManager.textEffectiveTime<8 && sendMsgManager.textEffectiveTime > 2)
        {
            [_timePicker selectRow:sendMsgManager.textEffectiveTime-3 inComponent:0 animated:NO];
        }
        
        [timePicker release];
    }
    
    if (_smileView)
    {
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.25
                         animations:^{
                             _smileView.frame = CGRectMake(0,__MainScreen_Height-44, 320, 216);
                             _inputBar.frame = CGRectMake(0, _timePicker.frame.origin.y-_inputBar.frame.size.height, 320, _inputBar.frame.size.height);
                         }
                         completion:^(BOOL finished) {
                             
                             if(!self.isShowSmile)
                             {
                                 self.isShowSmile = YES;
                                 [_smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
                             }
                             if(!self.isShowPlus)
                             {
                                 self.isShowPlus = YES;
                                 [_plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
                             }
                             self.isCloseInputBar = YES;
                         }];
    }
    else
    {
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.25
                         animations:^{
                             _inputBar.frame = CGRectMake(0, _timePicker.frame.origin.y-_inputBar.frame.size.height, 320, _inputBar.frame.size.height);
                         }
         ];
    }
    
    _timePicker.hidden = NO;
}

#pragma mark - 点击对话框左边语音按钮
//点击左侧录音按钮后的处理方法
- (void)switchVoice:(UIButton *)button
{
    self.isShowSound = !self.isShowSound;
    static CGFloat height = 0;
    
    if (height < (NSInteger)_inputBar.frame.size.height)
    {
        height = _inputBar.frame.size.height;
    }
    
    [UIView setAnimationsEnabled:YES];
    [UIView animateWithDuration:.1
                     animations:^{
                         _smileView.frame = CGRectMake(0,__MainScreen_Height, 320, 0);
                         _inputBar.frame = CGRectMake(0, __MainScreen_Height-44-44, 320, 44);
                     }
     ];
    [_smileView removeFromSuperview];
    _smileView = nil;
    
    if(self.isShowSound)
    {
        _inputBar.frame =CGRectMake(0, _inputBar.frame.origin.y,320, height);
        [_inputView.textView becomeFirstResponder];
        height = 0;
        
        [self switchBetweenHiddenAndvisible];
        
        [_actionButton setImage:[ThemeManager getThemeImage:@"btn_typevoice.png"] forState:UIControlStateNormal];
    }
    else
    {
        [_inputView.textView resignFirstResponder];
        
        [_smileButton2 setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
        [_plusButton2 setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
        [_actionButton2 setImage:[ThemeManager getThemeImage:@"btn_voicekey.png"] forState:UIControlStateNormal];
        
        [self switchBetweenHiddenAndvisible];
    }
    
    if (!self.isShowSmile)
    {
        self.isShowSmile = YES;
        [_smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
    }
    if (!self.isShowPlus)
    {
        self.isShowPlus = YES;
        [_plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    }
    if (!_timePicker.hidden)
    {
        _timePicker.hidden = YES;
    }
}

-(void)switchBetweenHiddenAndvisible
{
    UIView *tempView = nil;
    tempView = _inputBar.hiddenContentView;
    _inputBar.hiddenContentView = _inputBar.visibleContentView;
    _inputBar.visibleContentView = tempView;
    
    _inputBar.hiddenContentView.hidden = YES;
    _inputBar.visibleContentView.hidden = NO;
}

#pragma CFCube delegate method

- (void)cfCubeFlipDidStop:(CFCube *)cfCube
{
    _actionButton.enabled = YES;
}

#pragma - 键盘监听
//监听开启键盘
-(void)keyboardWillShow:(NSNotification *)note
{
    if (!self.isColseKeyboard)//如果self.isColseKeyboard是NO就不开启键盘
    {
        return;
    }
    
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // get a rect for the textView frame
    CGRect containerFrame = _inputBar.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    _inputBar.frame = containerFrame;
    
    //将“笑脸”按钮、“+”号按钮显示为“笑脸”、“+”
    self.isShowSmile = YES;
    self.isShowPlus = YES;
    [_smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
    [_plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    // commit animations
    [UIView commitAnimations];
}

//监听关闭键盘
-(void)keyboardWillHide:(NSNotification *)note
{
    if (!self.isColseKeyboard)//如果self.isColseKeyboard是NO就不开启键盘
    {
        return;
    }
    
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    if (self.isCloseInputBar)
    {
        // get a rect for the textView frame
        CGRect containerFrame = _inputBar.frame;
        containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;
        
        // animations settings
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:[duration doubleValue]];
        [UIView setAnimationCurve:[curve intValue]];
        
        // set views with new info
        _inputBar.frame = containerFrame;
    }
    
    // commit animations
    [UIView commitAnimations];
}

//关闭键盘等输入设备
- (void)tapped:(BanBu_MaskView *)maskView
{
    maskView.hidden = YES;
    
    if(_smileView)
    {
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.25
                         animations:^{
                             _smileView.frame = CGRectMake(0,__MainScreen_Height-44, 320, 216);
                             _inputBar.frame = CGRectMake(0, __MainScreen_Height-_inputBar.frame.size.height-44, 320, _inputBar.frame.size.height);
                             
                         }
                         completion:^(BOOL finished) {
                             
                             [_smileView removeFromSuperview];
                             _smileView = nil;
                             
                             if(!self.isShowSmile)
                             {
                                 self.isShowSmile = YES;
                                 [_smileButton setImage:[ThemeManager getThemeImage:@"btn_smlie.png"] forState:UIControlStateNormal];
                             }
                             if(!self.isShowPlus)
                             {
                                 self.isShowPlus = YES;
                                 [_plusButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
                             }
                             self.isCloseInputBar = YES;
                         }];
    }
    else if (!_timePicker.hidden)
    {
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.1
                         animations:^{
                             _timePicker.hidden = YES;
                             _inputBar.frame = CGRectMake(0, __MainScreen_Height-_inputBar.frame.size.height-44, 320, _inputBar.frame.size.height);
                         }
         ];
        
    }
    
    [_inputView.textView resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return MyAppDataManager.dialogs.count;
}

//设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *amsg = [MyAppDataManager.dialogs objectAtIndex:indexPath.row];
    //做映射
    if ([amsg valueForKey:KeyChatid])
    {
        [MyAppDataManager.cellRowMapDic setValue:[NSNumber numberWithInteger:indexPath.row] forKey:[amsg valueForKey:KeyChatid]];
        [MyAppDataManager.cellRowMapDic setValue:indexPath forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
    }
    
    if (indexPath.row==0)
    {
        if (![[amsg valueForKey:KeyShowtime] boolValue] && [[amsg valueForKey:KeyType] integerValue] != CHatCellTYpeHints)
        {
            return [VALUE(KeyHeight, amsg) floatValue] + TimeLabelHeight;
        }
    }
    
    NSLog(@"第几行:%d:%@",indexPath.row,amsg);
    return [VALUE(KeyHeight, amsg) floatValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithCapacity:10];
    [amsg addEntriesFromDictionary:self.profile];
    
    if([MyAppDataManager.dialogs count])
    {
        [amsg addEntriesFromDictionary:[MyAppDataManager.dialogs objectAtIndex:indexPath.row]];
    }
    
    if (indexPath.row == 0 && [[amsg valueForKey:KeyType] integerValue] != CHatCellTYpeHints)
    {
        [amsg setValue:[NSNumber numberWithBool:YES] forKey:KeyShowtime];
    }
    
    ChatCellType type = [[amsg valueForKey:KeyType] integerValue];
    BanBu_ChatSmileCell * cell1 = nil;
    
    switch (type)
    {
            //纯文字消息
        case ChatCellTypeText:
        {
            static NSString *SmileCellIdentifier = @"SmileCell";
            BanBu_SmileLabelCell *cell = (BanBu_SmileLabelCell *)[tableView dequeueReusableCellWithIdentifier:SmileCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_SmileLabelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SmileCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate = self;
            }
            
            [cell setChatCellInfo:amsg];
            
            cell1 = cell;
        }
            break;
            //图片消息
        case ChatCellTypeImage:
        {
            static NSString *ImageCellIdentifier = @"ImageCell";
            BanBu_ImageViewCell *cell = (BanBu_ImageViewCell *)[tableView dequeueReusableCellWithIdentifier:ImageCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_ImageViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            cell.mediaView.appChatController = self;
            cell1 = cell;
        }
            break;
            
            //地理位置消息
        case ChatCellTypeLocation:
        {
            static NSString *LocationCellIdentifier = @"LocationCell";
            BanBu_LocationCell *cell = (BanBu_LocationCell *)[tableView dequeueReusableCellWithIdentifier:LocationCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_LocationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LocationCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            NSArray *firstWords = [[amsg valueForKey:KeyContent] componentsSeparatedByString:@","];
            if(firstWords.count>1)
            {
                if([_latiArr count]!=0)
                {
                    [_latiArr removeAllObjects];
                }
                
                [_latiArr addObjectsFromArray:firstWords];
            }
            
            [cell setChatCellInfo:amsg];
            cell1 = cell;
        }
            break;
            
            //语音消息
        case ChatCellTypeVoice:
        {
            static NSString *VoiceCellIdentifier = @"VoiceCell";
            BanBu_VoiceViewCell *cell = (BanBu_VoiceViewCell *)[tableView dequeueReusableCellWithIdentifier:VoiceCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_VoiceViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:VoiceCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            cell.voiceView.tag = indexPath.row;
            cell.voiceView.appChatController = self;
            
            cell1 = cell;
        }
            break;
        case ChatCellTypeEmi:
        {
            static NSString *EmoCellIdentifier = @"EmoCell";
            BanBu_EmoViewCell *cell = (BanBu_EmoViewCell *)[tableView dequeueReusableCellWithIdentifier:EmoCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_EmoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:EmoCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            
            cell1 = cell;
        }
            break;
            //系统提示消息
        case CHatCellTYpeHints:
        {
            static NSString *HintsCellIdentifier = @"HintsCell";
            BanBu_HintsViewCell *cell = (BanBu_HintsViewCell *)[tableView dequeueReusableCellWithIdentifier:HintsCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_HintsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HintsCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            
            cell1 = cell;
        }
            break;
            //视频消息
        case ChatCellTypeVideo:
        {
            static NSString *VideoCellIdentifier = @"VideoCell";
            BanBu_VideoViewCell *cell = (BanBu_VideoViewCell *)[tableView dequeueReusableCellWithIdentifier:VideoCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_VideoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:VideoCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            cell.videoView.chatController = self;
            cell1 = cell;
            
        }
            break;
            //全屏播放的动画
        case ChatCellTypeFullScreenGif:
        {
            static NSString *FullSCellIdentifier = @"FullSCell";
            BanBu_FullScreenCell *cell = (BanBu_FullScreenCell *)[tableView dequeueReusableCellWithIdentifier:FullSCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_FullScreenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FullSCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            cell.fullGifView.chatController = self;
            cell1 = cell;
        }
            break;
            //复文本消息：广播通知、动态通知、推荐好友、推荐游戏、推荐应用、第三方插件消息、网址
        case ChatCellTypeSpecialText:
        {
            static NSString *SpecialCellIdentifier = @"SpecialCell";
            BanBu_SpecialTextCell *cell = (BanBu_SpecialTextCell *)[tableView dequeueReusableCellWithIdentifier:SpecialCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_SpecialTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SpecialCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            cell.chat = self;
            cell.specialView.chat = self;
            cell1 = cell;
        }
            break;
        default:
        {
            static NSString *SmileCellIdentifier = @"SmileCell";
            BanBu_SmileLabelCell *cell = (BanBu_SmileLabelCell *)[tableView dequeueReusableCellWithIdentifier:SmileCellIdentifier];
            if(cell == nil)
            {
                cell = [[[BanBu_SmileLabelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SmileCellIdentifier] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate=self;
            }
            
            [cell setChatCellInfo:amsg];
            
            cell1 = cell;
        }
            break;
    }
    //如果消息记录里面最后一条消息是已读状态，但是从对话传过来的不是已读状态时，更新对话表（注：该消息是自己发的）
    if (indexPath.row == MyAppDataManager.dialogs.count-1)
    {
        if (!cell1.atLeft)
        {
            if (![self.returnBtTitle isEqualToString:@"dialogueTitle"])
            {
                return cell1;
            }
            if ([VALUE(KeyStatus, amsg) intValue] != [[self.profile valueForKey:KeyStatus] intValue])
            {
                [MyAppDataManager updateStstus:MyAppDataManager.chatuid number:[NSNumber numberWithInt:[VALUE(KeyStatus, amsg) intValue]]];
            }
        }
    }
    
    return cell1;
}

#pragma mark - Table view delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([_inputView.textView isFirstResponder])
    {
        return;
    }
    
    if(self.tableView.contentInset.top != 0)
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.tableView.contentOffset.y<-30)
    {
        //松开加载更多
        BOOL isMore = [MyAppDataManager readMoreTwentyMessage];
        if(isMore)
        {
            [self.tableView reloadData];
            
            [self.tableView setContentOffset:CGPointMake(0, 0)];
        }
    }
    
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
    
    if ([_inputView.textView isFirstResponder])
    {
        return;
    }
}

//tableView停止滚动时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"tableView滚动停止");
}


#pragma mark - 停止播放语音
//停止播放语音
-(BOOL)stopLastVoiceView:(int)row
{
    BanBu_VoiceViewCell *cell = (BanBu_VoiceViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    [cell.voiceView stopPlaying:nil];
    cell.voiceView.isPlay=NO;
    return YES;
}

#pragma mark - TextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [textView becomeFirstResponder];
    textView.scrollEnabled = NO;
    self.isCloseInputBar = YES;
    if(!self.previousTextViewContentHeight)
        self.previousTextViewContentHeight = textView.contentSize.height;
    textView.scrollEnabled = YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat maxHeight = [JSMessageInputView maxHeight];
    CGFloat textViewContentHeight = 0;
    if (IS_IOS_7)
    {
        CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, maxHeight)];
        textViewContentHeight = size.height;
    }
    else
    {
        textViewContentHeight = textView.contentSize.height;
    }
    
    BOOL isShrinking = textViewContentHeight < self.previousTextViewContentHeight;
    
    CGFloat changeInHeight = textViewContentHeight - self.previousTextViewContentHeight;
    
    if(!isShrinking && self.previousTextViewContentHeight == maxHeight)
    {
        changeInHeight = 0;
    }
    else
    {
        changeInHeight = MIN(changeInHeight, maxHeight - self.previousTextViewContentHeight);
    }
    
    if(changeInHeight != 0.0f)
    {
        [UIView setAnimationsEnabled:YES];
        [UIView animateWithDuration:0.25f
                         animations:^{
                             
                             if(isShrinking)
                             {
                                 [_inputView adjustTextViewHeightBy:changeInHeight];
                             }
                             else
                             {
                                 [_inputView adjustTextViewHeightBy:changeInHeight];
                             }
                             
                             [self setInputViewFrame:changeInHeight];
                             self.sendtext= NO;
                         }
         ];
        
        self.previousTextViewContentHeight = MIN(textViewContentHeight, maxHeight);
    }
    
    if (IS_IOS_7)
    {
        UITextRange * range =  textView.selectedTextRange;
        
        //2014年09月25日13:53:59 在ios8下面不行,但是隐藏的话ios7不行
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)
        {
            _inputView.textView.text = textView.text;
        }
        [_inputView.textView setSelectedTextRange:range];
        
        if (isShrinking)
        {
            [_inputView.textView setContentOffset:CGPointMake(0, 0)];
        }
        if (textView.text.length <=0)
        {
            [textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -10)];
        }
    }
    else
    {
        if (textView.text.length <=0)
        {
            [textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -6)];
        }
    }
}

//设置输入框部分整体的frame
- (void)setInputViewFrame:(NSInteger)changeInHeight
{
    if (self.sendtext== YES && changeInHeight<=0)
    {
        return;
    }
    if (changeInHeight==0)
    {
        return;
    }
    NSLog(@"changeInHeight:%d",changeInHeight);
    if (changeInHeight>0)
    {
        changeInHeight+=1;
    }
    else
    {
        changeInHeight-=1;
    }
    
    
    CGRect r = _inputBar.visibleContentView.frame;
    r.size.height += changeInHeight;
    _inputBar.visibleContentView.frame = r;
    
    r = _inputView.frame;
    r.size.height += changeInHeight;
    r.origin.y = 7;
    _inputView.frame = r;
    
    _inputView.textView.backgroundColor = [UIColor clearColor];
    
    r = _inputBar.frame;
    r.size.height +=changeInHeight;
    _inputBar.frame = CGRectMake(0, _inputBar.frame.origin.y-changeInHeight, 320,r.size.height);
    
    r = _inputView.buttonImage.frame;
    r.size.height += changeInHeight;
    _inputView.buttonImage.frame = r;
    _inputView.buttonImage.image = [UIImage inputSlider:_inputView.buttonImage.frame];
    _inputView.buttonImage.userInteractionEnabled = YES;
}

//初始化输入框的frma
- (void)initInputViewFrame
{
    _inputView.frame =CGRectMake(_actionButton.frame.origin.x+60, 7,185, 30.0);
    _inputView.textView.frame = CGRectMake(17.5, 0,155, 30.0);
    [_inputView.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -10)];
    _inputBar.visibleContentView.frame = CGRectMake(0, 0, 320, 44);
    _inputBar.frame = CGRectMake(0, _inputBar.frame.origin.y+(_inputBar.frame.size.height-44),320,44);
    if (_inputView.snapText)
    {
        _inputView.buttonImage.frame = CGRectMake(_inputView.buttonImage.frame.origin.x, 0.6, 20, 27.4);
    }
    else
    {
        _inputView.buttonImage.frame = CGRectMake(_inputView.buttonImage.frame.origin.x, 1, 20, 27.4);
    }
    _inputView.buttonImage.image = [UIImage inputSlider:_inputView.buttonImage.frame];
}

//检测是否发送文本信息
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        if (_inputView.textView.text.length>400)
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"textLimite", nil) activityAnimated:NO duration:1.0];
            return NO;
        }
        
        //检测彩蛋
        [self easteregg:_inputView.textView.text];
        
        if(![[_inputView.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""])
        {
            sendMsgManager.snapText = _inputView.snapText;
            sendMsgManager.textEffectiveTime = [_timeLabel.text integerValue];
            if (sendMsgManager.textEffectiveTime<3)
            {
                sendMsgManager.textEffectiveTime = 3;
            }
            
            if (sendMsgManager.snapText)//是否是阅后即焚信息
            {
                [sendMsgManager sendOneMsg:_inputView.textView.text type:ChatCellTypeText filePathExtension:nil From:@"snap"];
            }
            else
            {
                //                NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
                //                [formatter setDateFormat:@"yyyy-MM-dd HH.mm.ss.SSS"];
                //                NSLog(@"检测前：%@",[formatter stringFromDate:[NSDate date]]);
                //
                //                //IsMinGanWord：检查不文明用语
                //                if ([[MyAppDataManager IsMinGanWord:_inputView.textView.text]isEqualToString:_inputView.textView.text])//不是不文明用语
                //                {
                [sendMsgManager sendOneMsg:_inputView.textView.text type:ChatCellTypeText filePathExtension:nil From:@"mo"];
                //                }
                //                else//是不文明用语
                //                {
                //                    NSLog(@"检测后：%@",[formatter stringFromDate:[NSDate date]]);
                //                    [sendMsgManager sendOneMsg:[MyAppDataManager IsMinGanWord:_inputView.textView.text] type:ChatCellTypeText filePathExtension:nil From:@"bw"];//bw：badword
                //                }
            }
            
            _inputView.textView.text = nil;
            [_inputView.textView setContentSize:CGSizeMake(165, 22)];
            self.previousTextViewContentHeight = 36;
            self.sendtext = YES;
            [self initInputViewFrame];
            if (IS_IOS_7)
            {
                [_inputView.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -10)];
            }
            else
            {
                [_inputView.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -6)];
            }
        }
        return NO;
    }
    else
    {
        if (_inputView.textView.text.length>400)
        {
            _inputView.textView.text = [_inputView.textView.text substringToIndex:400];
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"textLimite", nil) activityAnimated:NO duration:1.0];
            return NO;
        }
        return YES;
    }
}

#pragma mark - UIPickerViewDataSource 、UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return self.timeArray.count;
            break;
        default:
            return 4;
            break;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.timeArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _timeLabel.text = [NSString stringWithFormat:@"%d",row+3];
    sendMsgManager.textEffectiveTime = [_timeLabel.text integerValue];
}

#pragma mark - BanBu_SmileView Delegate “+”号键盘BanBu_SmileView的代理方法，选择破冰语或表情后的回调方法
//  BanBu_SmileView的代理方法，选择破冰语或表情后的回调方法
-(void)banBu_ActionView:(BanBu_SmileView *)actionView didInputBrand:(UIButton *)actionBrand isAdd:(BOOL)add
{
    //检查是否是好友、是否是VIP
    switch (actionBrand.tag)
    {
        case 0://拍照、摄像
        case 1://相册
        case 8://阅后即焚
        case 2://涂鸦
        {
            if (![sendMsgManager VIPCheck])
            {
                return;
            }
        }
            break;
        default:
            break;
    }
    
    //校验通过后自行
    switch (actionBrand.tag)
    {
        case 0://拍照、视频
        {
            UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"funLabel", nil),NSLocalizedString(@"recordVideo", nil), nil];
            actionSheet.tag = 20001;
            
            [actionSheet showInView:self.view];
            [actionSheet release];
        }
            break;
        case 1://相册
        {
            UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"phoneAlbume", nil),NSLocalizedString(@"HalfareaAlbume", nil), nil];
            actionSheet.tag = 20002;
            
            [actionSheet showInView:self.view];
            [actionSheet release];
        }
            break;
        case 2://涂鸦
        {
            BanBu_GraffitiController *aGraff=[[BanBu_GraffitiController alloc]initWithImage:nil andSourceType:1];
            //            [self presentViewController:aGraff animated:YES];
            [self.navigationController pushViewController:aGraff animated:YES];
            [aGraff release];
            aGraff = nil;
        }
            break;
        case 3://发送名片
        {
            BanBu_FriendListController * friendController = [[BanBu_FriendListController alloc]init];
            friendController.isVisitingCard = YES;
            [self.navigationController pushViewController:friendController animated:YES];
            [friendController release];
            //跳转到查找好友界面，点选好友后发送消息
        }
            break;
        case 4://聊天助手
        {
            BanBu_SearchIceViewController *aSearch = [[BanBu_SearchIceViewController alloc]init];
            [self.navigationController pushViewController:aSearch animated:YES];
            [aSearch release];
        }
            break;
        case 5://收藏
        {
            self.isColseKeyboard = NO;
            BanBu_ManuscriptViewController * manusscript = [[BanBu_ManuscriptViewController alloc]init];
            manusscript.appChatController = self;
            [self.navigationController pushViewController:manusscript animated:YES];
            [manusscript release];
            
        }
            break;
        case 6://位置
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"sendLocation", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"confirmNotice", nil), nil];
            alert.tag=101010;
            [alert show];
            [alert release];
        }
            break;
        case 7://魔法工具箱
        {
            BanBu_MagicKitViewController * magicKit = [[BanBu_MagicKitViewController alloc]init];
            magicKit.chat = self;
            self.isColseKeyboard = NO;
            [self.navigationController pushViewController:magicKit animated:YES];
            [magicKit release];
        }
            break;
        case 8://发送阅后即焚
        {
            BanBu_SnapController * snapController = [[BanBu_SnapController alloc]init];
            BanBu_MWNavigationController * nav = [[BanBu_MWNavigationController alloc]initWithRootViewController:snapController];
            
            [self.navigationController presentViewController:nav animated:YES];
            [snapController release];
            [nav release];
        }
            break;
        case 9://魔法文字,功能未实现
        {
            self.isColseKeyboard = NO;
            BanBu_MagicWordsViewController * magicWordsController = [[BanBu_MagicWordsViewController alloc]init];
            magicWordsController.appChatController = self;
            [self.navigationController pushViewController:magicWordsController animated:YES];
            [magicWordsController release];
            
        }
            break;
        default:
            break;
    }
}

#pragma mark - ChatCellDelegate  跳转到聊天助手、涂鸦、魔法工具箱
// 显示破冰语的东东
-(void)pushTheNextViewController:(NSString *)indext
{
    if([indext isEqualToString:@"pb"])
    {
        //聊天助手
        BanBu_SearchIceViewController *search=[[BanBu_SearchIceViewController alloc]init];
        [self.navigationController pushViewController:search animated:YES];
        [search release];
    }
    else if([indext isEqualToString:@"ty"])
    {
        //涂鸦
        BanBu_GraffitiController *aGraff=[[BanBu_GraffitiController alloc]initWithImage:nil andSourceType:1];
        [self.navigationController pushViewController:aGraff animated:YES];
        //        [self presentViewController:aGraff animated:YES];
        [aGraff release];
    }
    else if ([indext isEqualToString:@"mg"])
    {
        //魔法工具箱
        BanBu_MagicKitViewController * magicKit = [[BanBu_MagicKitViewController alloc]init];
        magicKit.chat = self;
        self.isColseKeyboard = NO;
        [self.navigationController pushViewController:magicKit animated:YES];
        [magicKit release];
    }
    else if ([indext isEqualToString:@"snap"])
    {
        BanBu_SnapController * snapController = [[BanBu_SnapController alloc]init];
        BanBu_MWNavigationController * nav = [[BanBu_MWNavigationController alloc]initWithRootViewController:snapController];
        [snapController release];
        [self.navigationController presentViewController:nav animated:YES];
        [nav release];
    }
    else if([indext isEqualToString:@"store"])//表情商店
    {
        BanBu_EmoStoreViewController * emoController = [[BanBu_EmoStoreViewController alloc]init];
        [self.navigationController pushViewController:emoController animated:YES];
        [emoController release];
    }
}

//阅后即焚
-(void)showSnapImageTabeCell:(BanBu_SmileLabelCell *)sendert
{
    [MyAppDataManager.readedUserArray addObject:sendert.userid];
    
    //发送已读状态
    if (AppComManager.netStatus!= NotReachable)
    {
        if (MyAppDataManager.readedUserArray.count > 0)
        {
            [MyAppDataManager sendReadedStatus:MyAppDataManager.readedUserArray];
            [MyAppDataManager.readedUserArray removeAllObjects];
        }
    }
    
    if (sendert.type == ChatCellTypeImage)    //snapImage
    {
        if (_snapImageView == nil)
        {
            self.snapImageView = [[[BanBu_SnapImageView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height+20)]autorelease];
        }
        
        _snapImageView.userInteractionEnabled = NO;
        _snapImageView.backgroundColor = [UIColor clearColor];
        UIImage * image = [MyAppDataManager msgImageForImageUrlStr:sendert.content];
        _snapImageView.snapImageView.image = image;
        
        [_snapImageView countdownCounter:sendert.effectiveTime];
        
        [self.navigationController.view addSubview:_snapImageView];
        
        //从数据库、界面消除本次图片消息
        [self countdownCounter:sendert.effectiveTime withTabeCell:sendert];
    }
    else if(sendert.type == ChatCellTypeVideo)//snapVideo
    {
        self.cell = (BanBu_VideoViewCell *)sendert;
        NSString * path = [NSString stringWithFormat:@"%@.mp4",[AppComManager pathForVideoMsgMedia:sendert.content]];
        
        self.movieController = [[[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:path]] autorelease];
        self.movieController.view.frame = CGRectMake(0, -20, 320, __MainScreen_Height+40);
        [self.movieController prepareToPlay];
        [UIApplication sharedApplication].statusBarHidden = YES;
        
        [self.navigationController.view addSubview:self.movieController.view];
        
        //从数据库、界面消除本次视频消息
        [self countdownCounter:sendert.effectiveTime withTabeCell:sendert];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissMovie:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    }
    else if (sendert.type == ChatCellTypeText)//snapText
    {
        //一定时间后消除显示的文本
        [self countdownCounter:sendert.effectiveTime withTabeCell:sendert];
    }
}

//倒计时，本方法实现文本型消息、图片、视频的倒计时消息
-(void)countdownCounter:(NSInteger)effectiveTime withTabeCell:(BanBu_SmileLabelCell *)sendert
{
    //如果正在播放悄悄话，就返回
    if (!sendert.snapTimeLabel.hidden)
    {
        return;
    }
    
    if (sendert.atLeft)
    {
        if (sendert.type == ChatCellTypeText)
        {
            CGFloat height = [BanBu_SmileLabel heightForText:[MyAppDataManager IsInternationalLanguage:sendert.smileSnapLabel]]+2*CellMarge+18;
            if (sendert.showTime)
            {
                height += TimeLabelHeight;
            }
            
            NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:sendert.chatid] integerValue];
            NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:row]];
            [amsg setValue:[NSNumber numberWithInt:height] forKey:KeyHeight];
            [amsg setValue:[NSNumber numberWithBool:YES] forKey:@"changanhou"];
            
            [MyAppDataManager.dialogs replaceObjectAtIndex:row withObject:amsg];
            
            [self.tableView reloadRowsAtIndexPaths:@[ [self.tableView indexPathForCell:sendert]] withRowAnimation:UITableViewRowAnimationNone];
            return;
        }
        else
        {
            sendert.backgroundTime.image = [UIImage imageNamed:@"sexangle_black.png"];
            sendert.backgroundTime.hidden = NO;
            sendert.snapTimeLabel.textColor = [UIColor whiteColor];
        }
    }
    else
    {
        if (sendert.type == ChatCellTypeText)
        {
            sendert.lockImage.hidden = YES;
        }
        sendert.backgroundTime.hidden = YES;
        sendert.snapTimeLabel.textColor = [UIColor blackColor];
    }
    
    __block int timeout = effectiveTime; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    sendert.snapTimeLabel.hidden = NO;
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0)//倒计时结束，关闭
        {
            dispatch_source_cancel(_timer);
            dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                sendert.snapTimeLabel.textColor = [UIColor blackColor];
                sendert.snapTimeLabel.hidden = YES;
                sendert.backgroundTime.hidden = YES;
                NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithCapacity:3];
                [amsg setValue:sendert.userid forKey:KeyFromUid];//存cell中保存的userid。不使用MyAppDataManager.chatuid
                [amsg setValue:sendert.chatid forKey:KeyChatid];
                [amsg setValue:sendert.content forKey:KeyContent];
                
                //从数据库中删除本条消息
                [MyAppDataManager deleteOneChattingRecordOfOnePerson:amsg];
                [MyAppDataManager deleteTalkRecordOfOnePerson:amsg];
                
                //刷新界面
                if (MyAppDataManager.chatuid && [MyAppDataManager.chatuid isEqualToString:sendert.userid])
                {
                    //从界面消除本条消息
                    [MyAppDataManager.appChatController removeRow:sendert];
                }
            });
        }
        else
        {
            NSString *strTime = [NSString stringWithFormat:@"%d",timeout];
            NSInteger time = timeout;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if(MyAppDataManager.appChatController == nil)
                {
                    timeout = 0;
                }
                //设置界面的按钮显示 根据自己需求设置
                if (time<=3)
                {
                    if (!sendert.atLeft)
                    {
                        sendert.snapTimeLabel.textColor = [UIColor redColor];
                    }
                    else
                    {
                        sendert.snapTimeLabel.textColor = [UIColor whiteColor];
                        sendert.backgroundTime.image = [UIImage imageNamed:@"sexangle_red.png"];
                    }
                }
                sendert.snapTimeLabel.text = strTime;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

//将本行从tableView中移除，
-(void)removeRow:(BanBu_ChatSmileCell *)sendert
{
    if (![MyAppDataManager.cellRowMapDic valueForKey:sendert.chatid])
    {
        return;
    }
    
    NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:sendert.chatid] integerValue];
    
    if (row>=MyAppDataManager.dialogs.count)
    {
        return;
    }
    
    __block UITableView * tableView = MyAppDataManager.appChatController.tableView;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //设置界面的按钮显示 根据自己需求设置
        [MyAppDataManager.dialogs removeObjectAtIndex:row];
        
        [tableView beginUpdates];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationMiddle];
        
        [tableView endUpdates];
        
        [tableView setContentSize:CGSizeMake(self.tableView.frame.size.width, self.tableView.contentSize.height-sendert.height)];
        
        [MyAppDataManager.cellRowMapDic removeObjectForKey:sendert.chatid];
        [MyAppDataManager.cellRowMapDic removeObjectForKey:[NSString stringWithFormat:@"%d",row]];
    });
}

//取消阅后即焚的视频播放
-(void)dismissMovie:(NSNotification *)notifi
{
    MPMoviePlayerController * mov = notifi.object;
    
    switch (mov.playbackState)
    {
        case MPMoviePlaybackStatePaused:
        case MPMoviePlaybackStateStopped:
        case MPMoviePlaybackStateInterrupted:
        {
            [self dismissSnapImageTabeCell:self.cell];
        }
            break;
            
        default:
            break;
    }
}

//取消阅后即焚的显示
-(void)dismissSnapImageTabeCell:(BanBu_ChatSmileCell *)sendert
{
    switch (sendert.type)
    {
        case ChatCellTypeImage:
        {
            _snapImageView.snapImageView.image = nil;
            [_snapImageView removeFromSuperview];
        }
            break;
        case ChatCellTypeVideo:
        {
            if (self.cell)
            {
                self.cell = nil;
            }
            else
            {
                return;
            }
            [UIApplication sharedApplication].statusBarHidden = NO;
            [self.movieController stop];
            [self.movieController.view removeFromSuperview];
            [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
        }
        default:
            break;
    }
}

//处理添加好友
-(void)didGetInfo:(NSString *)info
{
    if ([info rangeOfString:@"addfriend"].location != NSNotFound)//添加好友的
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
        //添加好友
        _isBlack = NO;
        
        NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithCapacity:5];
        
        [parDic setValue:[_profile valueForKey:@"userid"] forKey:LinkTouID];
        [parDic setValue:@"friend" forKey:Action];
        
        [AppComManager getBanBuData:BanBu_Set_Friend_Link par:parDic delegate:self];
        
        self.navigationController.view.userInteractionEnabled = NO;
    }
    else if ([info rangeOfString:@"myinfor"].location != NSNotFound)//跳转到自己的个人资料，申请vip
    {
        [[BanBu_VIPAlert shareInstance] GoVIPApplyViewAlertFor:self title:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"vipCanUse", nil)];
    }
    else if ([info rangeOfString:@"goverify"].location != NSNotFound)//邀请用户视频认证
    {
        [[BanBu_VIPAlert shareInstance] GoVerifyApplyViewAlertFor:self title:NSLocalizedString(@"videoVerify", nil) message:NSLocalizedString(@"verifyNoticeAlert", nil)];
    }
    else//其他情况弹出提示
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"lowVersion", nil) activityAnimated:NO duration:1.2];
    }
}

#pragma mark - 显示菜单
-(void)menuShow:(UIView *)sender tableCell:(BanBu_ChatSmileCell *)sendert
{
    [self.view becomeFirstResponder];
    
    _rowt = [[MyAppDataManager.cellRowMapDic valueForKey:sendert.chatid] integerValue];
    sendMsgManager.rowt = _rowt;
    
    _type=(int)sendert.type;
    
    if((sendert.statuss==0 || sendert.statuss==2)&& sendert.atLeft==NO)//本人发送的并且发送失败或正在发送的消息
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"resend", nil), nil];
        alert.tag=12345;
        [alert show];
        [alert release];
    }
    else if (sendert.atLeft == YES && (sendert.mediastatus == MediaStatusDownload || sendert.mediastatus == MediaStatusDownloadFaild))//对方发送的消息、并且自己正在下载中或下载失败
    {
        //下载失败或正在下载时点击弹对话框
        [self downloadFalidAlert];
    }
    else
    {
        UIAlertView *alertT;
        
        if(sendert.type == ChatCellTypeLocation || sendert.type == ChatCellTypeEmi || sendert.type == CHatCellTYpeHints ||[sendert.from isEqualToString:@"snap"])
        {
            alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil), nil];
        }
        else if(sendert.type == ChatCellTypeText || sendert.type == ChatCellTypeImage)//文字、图片可以响应所有操作，其他不能复制
        {
            //破冰语不能收藏
            if (![sendert.from isEqualToString:@"pb"])//涂鸦、拍照、本地照片,文本等，对方发的照片、文字都可以收藏
            {
                //2014年10月30日10:05:49 by yinlinlin 表情商店的表情,魔法工具箱不能复制，不能收藏
                if ([sendert.from isEqualToString:@"store"] || [sendert.from isEqualToString:@"mg"])
                {
                    alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"transmitButton", nil),nil];
                }
                else
                {
                    alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"copyButton", nil),NSLocalizedString(@"transmitButton", nil),NSLocalizedString(@"collectionButton", nil), nil];
                }
            }
            else
            {
                alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"copyButton", nil),NSLocalizedString(@"transmitButton", nil), nil];
            }
        }
        else if (sendert.type == ChatCellTypeVoice)
        {
            alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"transmitButton", nil),NSLocalizedString(@"collectionButton",nil), nil];
        }
        else if (sendert.type == ChatCellTypeVideo)
        {//长按视频
            alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"transmitButton", nil),NSLocalizedString(@"shareButton", nil), nil];
            
            
        }
        else
        {
            alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"transmitButton", nil), nil];
            
        }

        
        [alertT show];
        alertT.tag=66;
        [alertT release];
    }
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:))
    {
        return YES;
    }
    [super canPerformAction:action withSender:sender];
    if(action == @selector(reconnect1:)||action==@selector(share1:)||action==@selector(delete1:))
    {
        return YES;
    }
    return NO;
}

// 这是重新发送消息
-(void)reconnect1:(id)sender
{
    UIActionSheet *reconnect=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
    reconnect.tag=2345;
    [reconnect showInView:self.view.window];
    [reconnect release];
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

-(void)share1:(id)sender
{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

// 删除
-(void)delete1:(id)sender
{
    UIActionSheet *delete=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
    delete.tag=1234;
    [delete showInView:self.view.window];
    [delete release];
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

#pragma mark - UIActionSheetDelegate
// 进行删除的操作
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet.tag==1234)//长按：删除
    {
        if(buttonIndex==0)
        {
            NSMutableDictionary *deleteDialog = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:_rowt]];
            [deleteDialog setValue:MyAppDataManager.chatuid forKey:KeyFromUid];
            [MyAppDataManager deleteOneChattingRecordOfOnePerson:deleteDialog];//删表内容
            [MyAppDataManager.dialogs removeObjectAtIndex:_rowt];//删除数据源
            
            //更新界面
            [self.tableView beginUpdates];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:_rowt inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
            
            //如果是最后一条聊天记录，就要更新对话列表
            if([VALUE(VALUE(KeyChatid, deleteDialog), MyAppDataManager.cellRowMapDic) integerValue] == _rowt)
            {
                if(MyAppDataManager.dialogs.count)
                {
                    NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs lastObject]];
                    [peoDic setValue:MyAppDataManager.chatuid forKey:KeyFromUid];
                    [MyAppDataManager setTalkPeopleOne:peoDic];
                }
                else
                {
                    NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:deleteDialog];
                    [peoDic setValue:@"" forKey:KeyContent];
                    [peoDic setValue:[NSNumber numberWithInteger:ChatStatusNone] forKey:KeyStatus];
                    [peoDic setValue:MyAppDataManager.chatuid forKey:KeyFromUid];
                    [MyAppDataManager setTalkPeopleOne:peoDic];
                }
            }
            //因为删除的cell，要重新映射。
            [MyAppDataManager.cellRowMapDic removeAllObjects];
            for(int i=0;i<MyAppDataManager.dialogs.count;i++)
            {
                NSDictionary *amsg = [NSDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:i]];
                [MyAppDataManager.cellRowMapDic setValue:[NSNumber numberWithInteger:i] forKey:[amsg valueForKey:KeyChatid]];
            }
            [AppComManager cancalHandlesForObject:MyAppDataManager];
        }
    }
    else if(actionSheet.tag == 10101)//响应导航栏右上角编辑按钮
    {
        if(buttonIndex == 0)//加载更多
        {
            BOOL isMore = [MyAppDataManager readMoreTwentyMessage];
            if(isMore)
            {
                [self.tableView reloadData];
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
            }
        }
        else if(buttonIndex == 1)//清空聊天
        {
            [MyAppDataManager deleteAllChattingRecordsOfOnePerson:MyAppDataManager.chatuid];
            
            NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs lastObject]];
            [peoDic setValue:@"" forKey:KeyContent];
            [peoDic setValue:[NSNumber numberWithInteger:ChatStatusNone] forKey:KeyStatus];
            [peoDic setValue:MyAppDataManager.chatuid forKey:KeyFromUid];
            [peoDic setValue:[NSNumber numberWithInt:0] forKey:KeyType];
            [peoDic setValue:[NSNumber numberWithInt:0] forKey:KeyUnreadNum];
            
            [MyAppDataManager setTalkPeopleOne:peoDic];
            
            [MyAppDataManager.dialogs removeAllObjects];
            [MyAppDataManager.cellRowMapDic removeAllObjects];
            [self.tableView reloadData];
        }
        else if(buttonIndex == 2)//设置气泡、背景、主题
        {
            BanBu_ThemeAndBubbleViewController * theViewController = [[BanBu_ThemeAndBubbleViewController alloc]init];
            [self.navigationController pushViewController:theViewController animated:YES];
            [theViewController release];
        }
        else if(buttonIndex == 3)//拉黑
        {
            NSString *action = @"black";
            NSMutableDictionary *pars = [NSMutableDictionary dictionary];
            [pars setValue:[_profile valueForKey:@"userid"] forKey:LinkTouID];
            [pars setValue:action forKey:Action];
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", ni) activityAnimated:YES];
            [AppComManager getBanBuData:BanBu_Set_Friend_Link par:pars delegate:self];
            self.navigationController.view.userInteractionEnabled = NO;
            
            _isBlack = YES;
        }
        else if(buttonIndex == 4)//拉黑并举报
        {
            [_inputView.textView resignFirstResponder];
            BanBu_ReportView * aReportView = [[BanBu_ReportView alloc]initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height+20) andType:REPORT_USER];
            aReportView.delegate = self;
            [self.navigationController.view addSubview:aReportView];
            [aReportView release];
        }
    }
    else if(actionSheet.tag == 20001)//摄像、拍照
    {
        if (buttonIndex == 0)//拍照
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            if ([UIImagePickerController isSourceTypeAvailable:
                 UIImagePickerControllerSourceTypeCamera])
            {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            }
            [picker setAllowsEditing:NO];
            [self presentViewController:picker animated:YES];
            [picker release];
        }
        else if(buttonIndex == 1)//摄像
        {
            PBJViewController * pbjViewController = [[PBJViewController alloc] init];
            pbjViewController.quote = @"video";
            [self presentViewController:pbjViewController animated:YES];
            [pbjViewController release];
        }
    }
    else if (actionSheet.tag == 20002)//手机相册、半圆相册
    {
        if (buttonIndex == 0)//手机相册
        {
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [picker setAllowsEditing:NO];
            [self presentViewController:picker animated:YES];
            [picker release];
        }
        else if(buttonIndex == 1)//半圆相册
        {
            BanBu_PhotoAlbumViewController * photo = [[BanBu_PhotoAlbumViewController alloc]init];
            
            [self.navigationController pushViewController:photo animated:YES];
            [photo release];
        }
    }
    else//重发消息   响应actionSheet.tag=2345的重发
    {
        if(buttonIndex==0)
        {
            NSMutableDictionary *messageDic=[MyAppDataManager.dialogs objectAtIndex:_rowt];
            //重新发送
            [sendMsgManager ReconnectOneMsg:nil amsg:messageDic];
        }
    }
}

#pragma  mark- alert DeleteGate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==101010)//发送位置时弹出的alert
    {
        if(buttonIndex==1)
        {
            //发送位置信息
            [sendMsgManager sendOneMsg:nil type:ChatCellTypeLocation filePathExtension:nil From:@"mo"];
        }
        else
        {
            return;
        }
    }
    else if(alertView.tag==12345)//消息发送失败或一直在发送中时点击cell弹出的alert
    {
        if(buttonIndex==0)//取消
        {}
        else if (buttonIndex==1)//删除
        {
            alertView.hidden=YES;
            [self delete1:nil];
        }
        else        //重新发送
        {
            alertView.hidden=YES;
            [self reconnect1:nil];
        }
    }
    else if (alertView.tag == 20000)//对方发送的多媒体消息正在下载或下载失败
    {
        if(buttonIndex == 1)//删除
        {
            alertView.hidden=YES;
            
            [self delete1:nil];
        }
        else if(buttonIndex == 2)//重新下载
        {
            NSMutableDictionary * amsg =[NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:_rowt]];
            
            NSString * content = [amsg valueForKey:KeyContent];
            NSString * chatid = [amsg valueForKey:KeyChatid];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusDownload] forKey:KeyMediaStatus];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusDownload] forKey:KeyMediaStatus];
            
            [MyAppDataManager.dialogs replaceObjectAtIndex:_rowt withObject:amsg];
            [AppComManager getBanBuMedia:content forMsgID:chatid fromUid:MyAppDataManager.chatuid delegate:MyAppDataManager];
        }
    }
    else //长按cell弹出alert后的处理
    {
        if (buttonIndex)
        {
            NSDictionary *amsg = [NSDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:_rowt]];
            
            
            if([[amsg valueForKey:KeyType] intValue] == ChatCellTypeText || [[amsg valueForKey:KeyType] intValue] == ChatCellTypeImage)
            {
                if(buttonIndex == 1)//删除
                {
                    alertView.hidden=YES;
                    
                    [self delete1:nil];
                    return;
                }
                //2014年10月30日09:32:17 表情商店没有复制选项，所以判断时，加1
                if ([[amsg valueForKey:@"msgfrom"] isEqualToString:@"store"] || [[amsg valueForKey:@"msgfrom"] isEqualToString:@"mg"])
                {
                    buttonIndex = buttonIndex + 1;
                }
                if(buttonIndex == 2)//复制,可能复制的是文本、符号、图片、涂鸦，消息类型有两种type：text、image,msgfrom:mo,
                {
                    UIPasteboard *paste = [UIPasteboard generalPasteboard];
                    
                    if ([[amsg valueForKey:KeyType] integerValue]==1)
                    {
                        //2014年11月17日13:52:04 by yinlinlin 修改复制图片闪退,收藏图片和收藏表情保存的路径和普通对话中的图片不一样
                        if ([[amsg valueForKey:@"msgfrom"] isEqualToString:@"collectimage"])
                        {
                            NSString * imagePath = [AppComManager pathForCollectImage:[amsg valueForKey:@"content"]];
                            if ([UIImage imageWithContentsOfFile:imagePath])
                            {
                                paste.image = [UIImage imageWithContentsOfFile:imagePath];
                            }
                        }
                        else if ([[amsg valueForKey:@"msgfrom"] isEqualToString:@"collect"])
                        {
                            NSString * imagePath = [AppComManager pathForCollect:[amsg valueForKey:@"content"]];
                            if ([UIImage imageWithContentsOfFile:imagePath])
                            {
                                paste.image = [UIImage imageWithContentsOfFile:imagePath];
                            }
                        }
                        else
                        {
                            if ([MyAppDataManager msgImageForImageUrlStr:[amsg valueForKey:KeyContent]])
                                {
                                    paste.image = [MyAppDataManager msgImageForImageUrlStr:[amsg valueForKey:KeyContent]];
                                }
                        }
                        //修改完成
                        
                    }
                    else
                    {
                        paste.string = [amsg valueForKey:KeyContent];
                    }
                }
                /*
                 else if(buttonIndex == 3)//分享
                 {
                 #warning 分享：要屏蔽的功能
                 [self performSelector:@selector(afterDelayShare) withObject:nil afterDelay:0.5];
                 }
                 */
                else if(buttonIndex == 3)//转发
                {
                    //进入好友列表,选取好友、将本次的消息发给那些人，将这些人的userid存起来，然后同步该消息到数据库
                    //下一版再做；
                    BanBu_TransmitViewController * TransmitController = [[BanBu_TransmitViewController alloc]init];
                    NSMutableDictionary * amsg1 = [self packagingTransmitMsg:amsg];
                    TransmitController.chatController = self;
                    TransmitController.msgDic = amsg1;
                    [self.navigationController pushViewController:TransmitController animated:YES];
                    [TransmitController release];
                }
                else if (buttonIndex == 4)//收藏
                {
                    //收藏图片、文字、语音
                    [self collectCustImageOrWords];
                }
            }
            else if([[amsg valueForKey:KeyType] intValue] == ChatCellTypeVoice)
            {//语音
                if(buttonIndex == 1)//删除
                {
                    alertView.hidden=YES;
                    
                    [self delete1:nil];
                }
                /*
                 else if(buttonIndex == 2)//分享
                 {
                 #warning 分享：要屏蔽的功能
                 [self performSelector:@selector(afterDelayShare) withObject:nil afterDelay:0.5];
                 }
                 */
                else if(buttonIndex == 2)//转发
                {
                    //进入好友列表,选取好友、将本次的消息发给那些人，将这些人的userid存起来，然后同步该消息到数据库
                    //下一版再做；
                    BanBu_TransmitViewController * TransmitController = [[BanBu_TransmitViewController alloc]init];
                    
                    //打包将要转发消息的数据结构
                    NSMutableDictionary * amsg1 = [self packagingTransmitMsg:amsg];
                    TransmitController.chatController = self;
                    
                    TransmitController.msgDic = amsg1;
                    
                    [self.navigationController pushViewController:TransmitController animated:YES];
                    [TransmitController release];
                }
                else if (buttonIndex == 3)//收藏
                {
                    //收藏图片、文字、语音
                    [self collectCustImageOrWords];
                }
            }
            else
            {
                //视频
                if(buttonIndex == 1)//删除
                {
                    alertView.hidden=YES;
                    
                    [self delete1:nil];
                }
                else if(buttonIndex == 2)//转发
                {
                    //进入好友列表,选取好友、将本次的消息发给那些人，将这些人的userid存起来，然后同步该消息到数据库
                    //下一版再做；
                    BanBu_TransmitViewController * TransmitController = [[BanBu_TransmitViewController alloc]init];
                    
                    //打包将要转发消息的数据结构
                    NSMutableDictionary * amsg1 = [self packagingTransmitMsg:amsg];
                    TransmitController.chatController = self;
                    
                    TransmitController.msgDic = amsg1;
                    
                    [self.navigationController pushViewController:TransmitController animated:YES];
                    [TransmitController release];
                }
                else//分享
                {
                    [_menu setExpanding:YES];
                    [self.view insertSubview:_menu atIndex:self.view.subviews.count - 1];
                    
                }
            }
        }
    }
}

//下载失败时弹出提示
-(void)downloadFalidAlert
{
    UIAlertView *alertT;
    
    alertT=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"reDownload", nil), nil];
    
    [alertT show];
    alertT.tag=20000;
    [alertT release];
}

//粘贴
-(void)paste:(id)sender
{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    
    UIPasteboard *paste = [UIPasteboard generalPasteboard];
    NSData * data = UIImageJPEGRepresentation(paste.image, 1);
    
    [sendMsgManager sendOneMsg:data type:ChatCellTypeImage filePathExtension:@"jpg" From:@"mo"];
}

#pragma mark - 打包消息
//转发消息时打包消息
-(NSMutableDictionary *)packagingTransmitMsg:(NSDictionary *)amsg
{
    NSMutableDictionary * saysDic = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSArray *mapArr = typeArrDefine;
    
    NSInteger type = [[amsg valueForKey:KeyType] integerValue];
    
    [saysDic setValue:VALUE(KeyContent, amsg) forKey:KeyContent];
    [saysDic setValue:[mapArr objectAtIndex:type] forKey:KeyType];
    [saysDic setValue:[amsg valueForKey:KeyShowFrom] forKey:KeyShowFrom];
    [saysDic setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:KeyBubbleID];
    
    //消息类型是视频时，添加缩略图字段
    if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeVideo || [[amsg valueForKey:KeyType] integerValue] == ChatCellTypeFullScreenGif)
    {
        [saysDic setValue:VALUE(KeyThumbnail, amsg) forKey:KeyThumbnail];
    }
    
    //在初始化
    NSString *jsonValue = [[CJSONSerializer serializer] serializeDictionary:saysDic];
    
    jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSMutableDictionary *amsg1 = [NSMutableDictionary dictionaryWithDictionary:amsg];
    [amsg1 setValue:jsonValue forKey:KeySays];
    [amsg1 setValue:MyAppDataManager.useruid forKey:KeyFromUid];
    [amsg1 setValue:[NSNumber numberWithInt:type] forKey:KeyType];
    return amsg1;
}

#pragma mark - 收藏

//收藏图片
-(void)collectCustImageOrWords
{
    //将图片复制到收藏文件夹CollectionFolder
    NSDictionary * amsg = [MyAppDataManager.dialogs objectAtIndex:_rowt];
    
    if ([[[amsg valueForKey:KeyContent] pathExtension] isEqualToString:@"gif"])
    {//收藏到表情
        [self saveToEmoCollection:amsg];
    }
    else//收藏到草稿
    {
        [self saveToManuscript:amsg];
    }
}

//收藏到表情
-(void)saveToEmoCollection:(NSDictionary *)amsg
{
    //获取收藏的表情信息
    NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
    NSMutableArray *  collectedEmoArr = [[NSMutableArray alloc]initWithArray:collectedEmoDic.allValues];
    
    //排序
    [collectedEmoArr sortUsingFunction:compare context:NULL];
    
    //本次收藏的表情
    NSMutableDictionary * emoDic = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString * name = [formatter stringFromDate:[NSDate date]];
    
    [FileManager copyItemAtPath:[AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]] toPath:[AppComManager pathForEmo:name withFolder:CollectionFolder] error:nil];
    
    NSString * contentPath = [AppComManager pathForCollect:[amsg valueForKey:KeyContent]];
    
    [FileManager copyItemAtPath:[AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]] toPath:contentPath error:nil];
    
    [emoDic setValue:[amsg valueForKey:KeyChatid] forKey:Keyid];
    [emoDic setValue:name forKey:KeyName];
    [emoDic setValue:[amsg valueForKey:KeyContent] forKey:KeyPath];
    
    [formatter release];
    
    //索引
    NSInteger index = [[[collectedEmoArr lastObject] valueForKey:KeyIndex] integerValue]+1;
    [emoDic setValue:[NSNumber numberWithInteger:index] forKey:KeyIndex];
    
    //后缀
    NSString * extension = [[amsg valueForKey:KeyContent] pathExtension];
    [emoDic setValue:extension forKey:KeyExtension];
    
    //归档
    [collectedEmoDic setValue:emoDic forKey:name];
    [NSKeyedArchiver archiveRootObject:collectedEmoDic toFile:CollectEmoInfoPath];
    
    //提交服务器保存
    collectedEmoDic = [NSMutableDictionary dictionaryWithCapacity:2];
    
    NSString *content = [[CJSONSerializer serializer] serializeDictionary:emoDic];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    [collectedEmoDic setValue:content forKey:KeyContent];
    [AppComManager getBanBuDataWIthCollectEmo:BanBu_AddCollectEmo_ByUser par:collectedEmoDic delegate:MyAppDataManager];
    
    //刷新收藏的表情键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshCollectedEmo object:nil];
    
    [collectedEmoArr release];
}

#pragma mark - 收藏到草稿
//收藏到草稿
-(void)saveToManuscript:(NSDictionary *)amsg
{
    //收藏
    NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithCapacity:8];
    
    [parDic setValue:[amsg valueForKey:KeyContent] forKey:KeyContent];
    
    if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeVoice)
    {
        [parDic setValue:[NSNumber numberWithInt:MsgTypeVoice] forKey:KeyType];
    }
    else
    {
        [parDic setValue:[amsg valueForKey:KeyType] forKey:KeyType];
    }
    
    [parDic setValue:MyAppDataManager.chatuid forKey:KeyFromUidTalk];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * collectedTime = [formatter stringFromDate:[NSDate date]];
    
    [parDic setValue:collectedTime forKey:KeyCollectAmsgTime];
    
    //提交服务器
    [AppComManager getBanBuDataWIthCollectEmo:BanBu_AddCollectAmsg_ByUser par:parDic delegate:MyAppDataManager];
    
    if([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeImage)//收藏的是图片
    {    //收藏图片是要把图片转存到收藏草稿的文件夹ManuscriptFolder
        NSString * newFilePath = [AppComManager pathForCollectImage:ManuscriptFolder];
        NSString * olderFilePath = [AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]];
        //拷贝文件到收藏文件夹
        [FileManager copyItemAtPath:olderFilePath toPath:newFilePath error:nil];
    }
    else if([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeVoice)//收藏的是语音
    {    //收藏图片是要把图片转存到收藏草稿的文件夹ManuscriptFolder
        NSString * newFilePath = [AppComManager pathForCollectImage:ManuscriptFolder];
        NSString * olderFilePath = [AppComManager pathForMsgMedia:[amsg valueForKey:KeyContent]];
        //拷贝文件到收藏文件夹
        [FileManager copyItemAtPath:olderFilePath toPath:newFilePath error:nil];
    }
}

#pragma mark  - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo
{
    NSData *data = nil;
    
    data = UIImageJPEGRepresentation(image, 0.7);
    
    if (image.size.width>1500 || image.size.height>1500)
    {
        image = [MyAppDataManager scaleImage:image proportion:3];
    }
    else if (image.size.width>1000 || image.size.height > 1000)
    {
        image = [MyAppDataManager scaleImage:image proportion:1];
    }
    
    data = UIImageJPEGRepresentation(image, 0.7);
    if(data.length>100*1024)
    {
        NSData * date1 = nil;
        date1 = UIImageJPEGRepresentation(image, 0.6);
        data = date1;
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        [sendMsgManager sendOneMsg:data type:ChatCellTypeImage filePathExtension:@"jpg" From:@"mo"];
        [picker dismissModalViewControllerAnimated:YES];
        return;
    }
    
    
    BanBu_PhotoViewController * photo = [[BanBu_PhotoViewController alloc]init];
    photo.image = [UIImage imageWithData:data];
    photo.picker = picker;
    photo.type = 0;
    photo.enablePost = YES;
    [picker setNavigationBarHidden:YES animated:YES];
    [picker pushViewController:photo animated:YES];
    [photo release];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES];
}

#pragma mark - 录音
- (void)record:(UILongPressGestureRecognizer *)longPress
{
    UIButton *button = (UIButton *)longPress.view;
    
    if(button.selected)
    {
        CGPoint point = [longPress locationInView:_recordView];
        if(longPress.state == UIGestureRecognizerStateEnded)
        {
            button.selected = NO;
            [_recordView touchesEndInView:point];
            _recordView = nil;
        }
        else
            [_recordView touchesMovedInView:point];
        
        return;
    }
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        button.selected = YES;
        RecordView *recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height)];
        if (IS_IOS_7)
        {
            recordView.frame = CGRectMake(0, 20, 320, __MainScreen_Height);
        }
        _recordView = recordView;
        NSString *fileName = [NSString stringWithFormat:@"%i-%@.%@",MyAppDataManager.dialogs.count,MyAppDataManager.chatuid,@"amr"];
        
        _recordView.audioPath = [AppComManager pathForMsgMedia:fileName];
        recordView.delegate = self;
        [self.navigationController.view addSubview:recordView];
        [recordView release];
    }
    
}

#pragma mark - 录音结束
- (void)recordView:(RecordView *)recordView recordDidCompleted:(NSData *)audioData recordTime:(int)duration
{
    //结束录音
    voiceButton.selected = NO;
    if([audioData length]<100 || (duration < 1))
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"recordshort", nil) activityAnimated:NO duration:1.0];
        return;
    }
    
    [[AVAudioSession sharedInstance] setActive:NO error: nil];
    [sendMsgManager sendOneMsg:audioData type:ChatCellTypeVoice filePathExtension:@"amr" From:@"mo"];
}

#pragma mark - 发送： 涂鸦、破冰语、图片、视频、表情、闪光字、翻译、魔法表情、火星文
-(void)sendMsgAllType:(NSNotification *)notifi
{
    [sendMsgManager sendMsgAllType:notifi];
}

-(void)goinToEmoStore:(BanBu_EmoKeyboard *)smileView withNextView:(NSString *)nextView
{
    if ([nextView isEqualToString:@"store"])
    {
        BanBu_EmoStoreViewController * emoController = [[BanBu_EmoStoreViewController alloc]init];
        [self.navigationController pushViewController:emoController animated:YES];
        [emoController release];
    }
    else if ([nextView isEqualToString:@"collect"])
    {
        BanBu_CollectionController *collection = [[BanBu_CollectionController alloc]init];
        [self.navigationController pushViewController:collection animated:YES];
        [collection release];
    }
}

#pragma mark - BanBu_EmoKeyboard 默认表情键盘输入处理
/**
 * @函数名称：
 * @函数描述：处理默认表情，字符，收藏和表情商店的表情处理
 * @输入参数：smileView:操作的界面；inputString：输入文字；del：是否是字符删除操作；smile：类型0:要输入的字符，1：默认表情；2：下载的表情
 * @输出参数：
 * @返回值：
 * @author：your name
 */
//发送表情
- (void)banBu_SmileView:(BanBu_SmileView *)smileView didInputSmile:(NSString *)inputString isDelete:(BOOL)del type:(int)smile
{
    //删除字符操作
    if(del)
    {
        if([_inputView.textView hasText])
        {
            if(smileView.inputedStr.count)
            {
                NSInteger deleteLength = [[smileView.inputedStr lastObject] length];
                _inputView.textView.text = [_inputView.textView.text stringByReplacingCharactersInRange:NSMakeRange(_inputView.textView.text.length-deleteLength,deleteLength) withString:@""];
                [smileView.inputedStr removeLastObject];
            }
            else
            {
                _inputView.textView.text = [_inputView.textView.text substringToIndex:_inputView.textView.text.length-1];
            }
        }
    }
    else
    {
        if(smile==0)
        {
            if(!self.previousTextViewContentHeight)
                self.previousTextViewContentHeight = _inputView.textView.contentSize.height;
            
            NSString * text = [_inputView.textView.text stringByAppendingString:inputString];
            _inputView.textView.text = text;
            [self textViewDidChange:_inputView.textView];
            
            [_inputView.textView scrollRectToVisible:CGRectMake(0, _inputView.textView.contentSize.height-15, _inputView.textView.contentSize.width, 10) animated:YES];
        }
        else if(smile == 1)
        {
            [sendMsgManager sendOneMsg:inputString type:ChatCellTypeEmi filePathExtension:@"emo" From:@"mo"];
        }
        else if (smile == 2)
        {
            //发送下载的表情
            [sendMsgManager sendOneMsg:inputString type:ChatCellTypeImage filePathExtension:@"gif" From:@"mo"];
        }
    }
}

-(void)BanBu_EmoViewInputSmile:(NSString *)inputStr type:(int)type filePathExtension:(NSString *)extension
{
    if(type)
    {
        [sendMsgManager sendOneMsg:inputStr type:ChatCellTypeImage filePathExtension:extension From:@"store"];
    }
    else
    {
        [sendMsgManager sendOneMsg:inputStr type:ChatCellTypeImage filePathExtension:extension From:@"collect"];
    }
}

-(void)sendCharactor
{
    if([[_inputView.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""])
    {
        return;
    }
    [sendMsgManager sendOneMsg:_inputView.textView.text type:ChatCellTypeText filePathExtension:nil From:@"mo"];
    
    _inputView.textView.text = nil;
    [_inputView.textView setContentSize:CGSizeMake(165, 22)];
    self.previousTextViewContentHeight = 36;
    self.sendtext = YES;
    [self initInputViewFrame];
    if (IS_IOS_7)
    {
        [_inputView.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -10)];
    }
    else
    {
        [_inputView.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -6)];
    }
    
}

#pragma mark - 接收其他用户发送的消息
//将消息显示到界面上 接别人的消息
-(void)insertInToTable:(NSArray *)amsgList
{
    //更新数据源，更新界面插入到uitableview 里面去
    NSMutableArray * indexPathArray = [NSMutableArray arrayWithCapacity:5];
    double height = 0;
    NSMutableString * content = [NSMutableString stringWithString:@""];
    
    //建立映射关系
    for (NSDictionary * amsg in amsgList)
    {
        [MyAppDataManager.dialogs addObject:amsg];
        NSLog(@"%@",MyAppDataManager.dialogs);
        [indexPathArray addObject:[NSIndexPath indexPathForRow:MyAppDataManager.dialogs.count-1 inSection:0]];
        height += [[amsg valueForKey:KeyHeight] floatValue];
        
        if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeText)
        {
            [content appendString:[amsg valueForKey:KeyContent]];
        }
    }
    
    if (indexPathArray.count<=0)
    {
        return;
    }
    
    if (content.length>0)
    {
        [self easteregg:content];
    }
    
    content = nil;
    
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
    
    if (IS_IOS_7)
    {
        //2014年09月29日16:34:09 by yinlinlin 修改跳动问题，暂时隐藏，不知道什么用处
        //        [self.tableView setContentSize:CGSizeMake(320, self.tableView.contentSize.height + height)];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MyAppDataManager.dialogs.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
    [self tableViewAutoOffset];
}

#pragma mark - 插入自己发送的消息
//将消息显示到界面上 显示自己发送的消息
-(void)insertInToTableByMySelf:(NSArray *)amsgList
{
    //更新数据源，更新界面插入到uitableview 里面去
    NSMutableArray * indexPathArray = [NSMutableArray arrayWithCapacity:5];
    double height = 0;
    BOOL me = NO;
    //建立映射关系
    for (NSDictionary * amsg in amsgList)
    {
        if ([amsg valueForKey:KeyMe])
        {
            me = YES;
        }
        
        NSLog(@"自己发送的消息:%@",amsg);
        [MyAppDataManager.dialogs addObject:amsg];
        [indexPathArray addObject:[NSIndexPath indexPathForRow:MyAppDataManager.dialogs.count-1 inSection:0]];
        height += [[amsg valueForKey:KeyHeight] floatValue];
    }
    
    if (indexPathArray.count<=0)
    {
        return;
    }
    
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
    if (IS_IOS_7)
    {
        [self.tableView setContentSize:CGSizeMake(320, self.tableView.contentSize.height + height)];
    }
    
    
    if ([_inputView.textView isFirstResponder] && me)
    {
        return;
    }
    
    [self tableViewAutoOffset];
}

#pragma mark - 彩蛋
-(void)easteregg:(NSString *)text
{
    if (_showEggs)
    {
        //正在播放彩蛋，返回
        return;
    }
    NSArray * array = [MyAppDataManager easteregg:text];
    
    if (array)
    {
        BOOL bl = [[array objectAtIndex:0] boolValue];
        //如果没找到图片就返回
        if (!bl)
        {
            return;
        }
        
        NSString * imagePath = [array objectAtIndex:1];
        NSString * musicPath = [array objectAtIndex:2];
        
        //显示彩蛋图片
        [self showSnowView:imagePath musicPath:musicPath];
    }
}

//显示彩蛋
-(void)showSnowView:(NSString *)imagePath musicPath:(NSString *)musicPath
{
    _showEggs = YES;
    BanBu_SnowView * snow = [[BanBu_SnowView alloc]initWithFrame:self.view.frame];
    snow.tag = 40004;
    snow.delegate = self;
    snow.userInteractionEnabled = NO;
    [snow initWithImagePath:imagePath musicName:musicPath];
    [snow statrOrStop:snow.start];
    [self.view addSubview:snow];
    
    [snow release];
    snow = nil;
}

//取消彩蛋
-(void)didFinishPlayingSnows:(BanBu_SnowView *)snowView
{
    _showEggs = NO;
    [snowView removeFromSuperview];
}

#pragma mark - AlertView 第一次跟他对话时弹出提示框
-(void)removeAlertView:(BanBu_AlertView *)alertView
{
    [alertView removeFromSuperview];
    
    __block UIView * bheaderView = _headerView;
    __block UITableView * btableView = self.tableView;
    [UIView animateWithDuration:0.3 animations:^{
        btableView.frame = CGRectMake(0, 0, 320, 64);
        btableView.tableHeaderView = bheaderView;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - BanBuRequestDelegate
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    //20141020
    if ([[resDic valueForKey:@"fc"] isEqualToString:@"get_short_url"]) {
        _shortUrl=[resDic valueForKey:@"shorturl"];
        [_shortUrl retain];
    }
    //20141020
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        _isBlack = NO;
        return;
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Sayhi_Rand])//从表情点击进入破冰语
    {
        if([[resDic valueForKey:@"ok"]boolValue])
        {
            NSArray *typeArr = [NSArray arrayWithObjects:@"text",@"image",@"sound", nil];
            NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
            [parDic setValue:[typeArr objectAtIndex:1] forKey:@"kind"];
            [parDic setValue:@"ＱＱ表情" forKey:@"keyword"];
            
            [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            
            BanBu_icePicController *pic = [[BanBu_icePicController alloc]initWithDictionary:resDic];
            
            pic.immediateExit = YES;
            if(![[parDic valueForKey:@"keyword"] isEqualToString:@""])
            {
                pic.title = NSLocalizedString(@"freeEmotion", nil);
            }
            
            pic.parDic = parDic;
            
            [self.navigationController pushViewController:pic animated:YES];
            [pic release];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Report_User])//拉黑并举报
    {
        if([[resDic valueForKey:@"ok"]boolValue])
        {
            NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
            [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
            
            [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
            [UserDefaults synchronize];
            
            if(!_isBlack)
            {
                if(_isBlack)
                {
                    [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:CGPointMake(0, 190) title:NSLocalizedString(@"blackAndReportOK", nil) activityAnimated:NO duration:1.0];
                }
            }
            else
            {
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:CGPointMake(0, 190) title:NSLocalizedString(@"blackAndReportOK", nil) activityAnimated:NO duration:1.0];
            }
            
            //删除该人的对话
            [MyAppDataManager deleteBlackDialog:[[resDic valueForKey:@"friendlist"] valueForKey:@"x"]];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Friend_Link])//拉黑或添加好友
    {
        self.navigationController.view.userInteractionEnabled = YES;
        if([[resDic valueForKey:@"ok"]boolValue])
        {
            NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
            [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
            
            [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
            [UserDefaults synchronize];
            
            if (_isBlack)
            {
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:CGPointMake(0, 190) title:NSLocalizedString(@"blackAndReportOK", nil) activityAnimated:NO duration:1.0];
                
                //删除该人的对话
                [MyAppDataManager deleteBlackDialog:[[resDic valueForKey:@"friendlist"] valueForKey:@"x"]];
                _isBlack = NO;
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"linkSuccess", nil)activityAnimated:NO duration:1.0];
            }
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Broadmaster_byid])//跳转到广播
    {
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
            [self jumpToBroadCast:resDic];//跳转到广播详情
        }
        else
        {
            [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1];
        }
        
    }
    else if([[resDic valueForKey:@"fc"] isEqualToString:@"get_location"])//获取用户的地理位置信息
    {
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            if([[[resDic valueForKey:@"result"]valueForKey:@"status"] isEqualToString:@"OK"])
            {
                if([[[resDic valueForKey:@"result"] valueForKey:@"results"] count] > 0)
                {
                    NSArray *results = [[[[resDic valueForKey:@"result"] valueForKey:@"results"] objectAtIndex:0] valueForKey:@"address_components"];
                    NSString *country = nil;
                    NSString *locality = nil;
                    
                    for(NSDictionary *dic in results)
                    {
                        NSString *type = [[dic valueForKey:@"types"] objectAtIndex:0];
                        
                        if(!country&&[type isEqualToString:@"country"])
                        {
                            country = [dic valueForKey:@"long_name"];
                        }
                        
                        if(!locality&&[type isEqualToString:@"administrative_area_level_1"])
                        {
                            locality = [dic valueForKey:@"long_name"];
                        }
                        
                        if(!locality&&[type isEqualToString:@"locality"])
                        {
                            locality = [dic valueForKey:@"long_name"];
                        }
                        
                    }
                    NSMutableString *result = [NSMutableString string];
                    
                    if(country) { [result appendString:country]; }
                    
                    if(locality){ [result appendFormat:@"-%@",locality]; }
                    
                    //设置地理位置
                    [self updateTitleWithString:result];
                }
                else
                {
                    [self updateTitleWithString:NSLocalizedString(@"getLocationFail", nil)];
                }
            }
            
            else
            {
                [self updateTitleWithString:NSLocalizedString(@"getLocationFail", nil)];
                
            }
        }
        else
        {
            [self updateTitleWithString:NSLocalizedString(@"getLocationFail", nil)];
        }
    }
}

#pragma mark - 跳转到广播
//跳转到广播
-(void)jumpToBroadCast:(NSDictionary *)resDic
{
    BanBu_DigiViewController *digi = nil;
    for(UIViewController *vc in [self.navigationController viewControllers])
        if([vc isKindOfClass:[BanBu_DigiViewController class]])
        {
            digi = (BanBu_DigiViewController *)vc;
            break;
        }
    if(digi)
    {
        [self.navigationController popToViewController:digi animated:YES];
    }
    else
    {
        NSMutableDictionary *proDic = [NSMutableDictionary dictionaryWithDictionary:[resDic valueForKey:@"actiondata"]];
        
        NSMutableDictionary *conDic = [[NSMutableDictionary alloc]initWithDictionary:[proDic valueForKey:@"actioninfor"]];
        NSMutableDictionary *mcontentDic = [NSMutableDictionary dictionaryWithDictionary:[AppComManager getAMsgFrom64String:[conDic valueForKey:@"mcontent"]]];
        
        [conDic setValue:mcontentDic forKey:@"mcontent"];
        [proDic setValue:conDic forKey:@"actioninfor"];
        
        digi = [[BanBu_DigiViewController alloc] initWithBroadcast:proDic];
        
        [self.navigationController pushViewController:digi animated:YES];
        [digi release];
        [conDic release];
    }
}

//拉黑并举报
-(void)reportAndPullBlack:(NSString *)message
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
    
    [pars setValue:[_profile valueForKey:@"userid"] forKey:ReportTouID];
    [pars setValue:message forKey:@"saytext"];
    
    [AppComManager getBanBuData:BanBu_Report_User par:pars delegate:self];
    _isBlack = YES;
}
#pragma mark - 选择分享平台
//zyfzyfzyf⬇️
-(void)quadCurveMenu:(QuadCurveMenu *)menu didSelectIndex:(NSInteger)idx
{
    
    [_menu setExpanding:NO];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _hud = [[MBProgressHUD alloc]initWithView:self.view];
        _hud.delegate = self;
        [_hud show:YES];
        //20141020
        NSString * shareText;
        NSString * urlStr;
        UIImage  * shareImg;
        NSDictionary *amsg = [NSDictionary dictionaryWithDictionary:[MyAppDataManager.dialogs objectAtIndex:_rowt]];
        NSInteger type=[[amsg valueForKey:@"type"] intValue];
        if (type==0) {//纯文字
            shareText=[NSString stringWithFormat:@"%@ %@",[amsg valueForKey:@"content"],_shortUrl];
            shareImg=nil;
            urlStr=nil;
        }
        else if (type==1)
        {//图片
            shareText=[NSString stringWithFormat:@"%@",_shortUrl];
            shareImg=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[amsg valueForKey:@"content"]]]];
            urlStr=[amsg valueForKey:@"content"];
        }
        else if(type==6)
        {//视频
            shareText=[NSString stringWithFormat:@"%@",_shortUrl];
            shareImg=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[amsg valueForKey:@"thumbnail"]]]];
            urlStr=[amsg valueForKey:@"content"];
        }
        else
        {
            shareText=nil;
            shareImg=nil;
            urlStr=nil;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_hud hide:YES];
            NSString *langauage=[MyAppDataManager getPreferredLanguage];
            if ([langauage isEqualToString:@"zh-Hans"]) {
                [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:idx WithText:shareText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
            }
            else
            {
                if (idx==1) {
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:6 WithText:shareText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
                }
                else
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:7 WithText:shareText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
            }
            //20141020
        });
    });
}

#pragma mark - HUDDelegate
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    [hud release];
    hud = nil;
}
//zyfzyfzyf⬆️


#pragma mark - 分享

- (void) performPublishAction:(void (^)(void)) action {
    // we defer request for permission to post to the moment of post, then we check for the permission
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        // if we don't already have the permission, then we request it now
        [FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                                   defaultAudience:FBSessionDefaultAudienceFriends
                                                 completionHandler:^(FBSession *session, NSError *error) {
                                                     if (!error) {
                                                         [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
                                                         
                                                         action();
                                                     }
                                                     //For this example, ignore errors (such as if user cancels).
                                                 }];
    } else {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
        
        action();
    }
    
}


- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    TKLoadingView *indictor = nil;
    for(indictor in self.view.subviews)
        if([indictor isKindOfClass:[TKLoadingView class]])
        {
            [indictor setActivityAnimating:NO withShowMsg:NSLocalizedString(@"shareSuccess", nil)];
            [indictor dismissAfterDelay:1.0 animated:YES];
        }
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    TKLoadingView *indictor = nil;
    for(indictor in self.view.subviews)
        if([indictor isKindOfClass:[TKLoadingView class]])
        {
            [indictor setActivityAnimating:NO withShowMsg:NSLocalizedString(@"errcode_fail", nil)];
            [indictor dismissAfterDelay:1.0 animated:YES];
        }
}

- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}

- (NSString *)loadAccessToken
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}
@end
